如何在java中检查和过滤不同值的组

时间:2014-06-27 10:16:49

标签: java conditional-statements

我有一个文本文件,其数据如下所示..

2;30;1;801;2;1951;195102;1111;
2;30;1;801;3;1621;162101;1111;
2;30;1;802;1;1807;180702;1111;
2;30;1;802;1;1807;180703;1111;
2;30;1;802;1;1807;180704;1111;
2;30;1;802;2;1101;110101;1111;
2;30;1;802;2;1139;113902;9999;
2;30;1;802;2;1948;194801;1111;
2;30;1;802;2;1948;194802;1111;
2;30;1;802;3;2477;247701;1111;
2;37;2;803;1;2006;200601;0000;
2;37;2;803;1;2006;200602;0000;
2;37;2;803;2;2005;200501 ;0000;

在我的程序中,我必须放置一个过滤器,然后显示,根据Row[3]对行进行分组,即Row[7]。我的列表应该在过滤后显示如下,例如仅针对802

802;1;1807;180702;1111;
802;1;1807;180703;1111;
802;1;1807;180704;1111;
802;2;1101;110101;1111;
802;2;1139;113902;9999;
802;2;1948;194801;1111;
802;2;1948;194802;1111;
802;3;2477;247701;1111;

类似于803

803;1;2006;200601;0000;
803;1;2006;200602;0000;
803;2;2005;200501 ;0000;

问题是Row[3]的值不是常数并且在组中的整个文件中保持变化,例如,一堆值是802,下一串804,806等等。应如上所示分组。 我已经有一个FileReader用于阅读该文件,但有人可以告诉我如何应用此过滤器的逻辑吗?

用于读取文件和将值放入列表中的代码

public ArrayList<Asset> getData() {

        ArrayList<Asset> list = new ArrayList<Asset>(); 
        try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
            String line;
            Asset sd = null;
            while ((line = reader.readLine()) != null ) {
                 String[] RowData = line.split(";");
                 if (RowData.length >= 19) {
                     sd = new Asset();
                    sd.setProductID(RowData[3]);
                    sd.setProductName(RowData[7]);
                    sd.setStatus(RowData[13]);
                    list.add(sd);
                    }
                }   
                return list;
                }

我很困惑在从RowData[3]

阅读时,为了在while循环中过滤reader而添加什么逻辑

1 个答案:

答案 0 :(得分:0)

首先用行[3] == 803(左右)过滤出行,然后根据行[7]进行排序,如

Collections.sort(filteredCsvRowsCollection,new Comparator<Integer[]>(){
   @Override
   public int compare(final Integer[] lhs,final Integer[] rhs) {
         if (lhs[7] > rhs[7]) { return 1; } 
         else if (lhs[7] < rhs[7]) { return -1; }
         else { return 0; }
     }
}

采用哪种方式 How to use Comparator in Java to sort