多个if语句添加到arrayList java

时间:2016-05-07 09:32:31

标签: java arraylist

我正在将文本文件读入我的班级。我想在满足if条件时添加到特定的arrayList。目前,arrayList继续被写入,我不知道为什么。这是代码:

通话类:

public String PatternPDF (String s) throws IOException, ClassNotFoundException {
        ArrayList<String>arr=new ArrayList<String>();
        for (String line : Files.readAllLines(Paths.get("Fields2Extract.txt"))){
            //System.out.println(line);
            arr.add(line);
        }
        for (String pattern:arr){
            OrganisePDF(pattern,s);
        }
        return pattern;
    }

arrayList类

public void  OrganisePDF (String pattern,String s) {
    ArrayList<String> Chicago =new ArrayList<String>();
    Pattern patternorganise = Pattern.compile(pattern);
    Matcher matcherpatternorganise_pattern = patternorganise.matcher(s);
    String h="";
            while (matcherpatternorganise_pattern.find()){
                 h=matcherpatternorganise_pattern.group(0);
                 all.add(h);
            }


            for (String n:all){
                if(n.contains("something good")||n.contains("a load of buses")){
                    n=n.replaceAll("\\n", "").trim();
                    Chicago.add(n);
                       }
            }

    System.out.prinln("Chicago"+Chicago);
}

这给了我

Chicago[something good]
Chicago[a load of buses]

而我希望

Chicago[something good,a load of buses]

2 个答案:

答案 0 :(得分:0)

你得到的是因为你没有在正则表达式的匹配中连接结果。

尝试将匹配项添加到stringbuilder中,然后在for循环中将其添加到芝加哥列表中:

StringBuilder sb = new StringBuilder();
for (String n:all){
    if(n.contains("something good")||n.contains("a load of buses")){
        n=n.replaceAll("\\n", "").trim();
        sb.append(n);
    }

}
Chicago.add(sb.toString());

答案 1 :(得分:0)

list.add(1, object1)
StringBuilder builder = new StringBuilder();
for (String n:all){
    if(n.contains("something good")||n.contains("a load of buses")){
        n=n.replaceAll("\\n", "").trim();
        builder.append(n);
        Chicago.add(0,builder.toString()); //this will add the data to a specific position
    }
}

我不知道你为什么要做这个奇怪的事情,但你可以这样尝试chicago.add(0,ojec);这会在每次调用时将数据添加到给定位置。