日期:2014-05-20  浏览次数:20779 次

求大神帮忙搞定
我现在有4组数据分别为:
new Ts("a", "b", "vv"));
new Ts("a", "b", "@@"));
new Ts("aa", "bb", "cc"));
new Ts("aa", "bb", "dd"));

  我已经分好组了,第一,第二元素相同的为一组,比如说new Ts("a", "b", "vv")),new Ts("a", "b", "@@")),这两个一组;new Ts("aa", "bb", "cc")),new Ts("aa", "bb", "dd"))这两个是一组。现在想实现的是,在每组中,如果第三个元素是@@的话,把这条记录写进txt。如果没有@@,那就写该组的头一条。
  我写的代码是这样的:
Java code

    /**
     * 分组
     * @param list
     * @return
     */
    public static List<List<Ts>> getGroup(List<Ts> list){
        List<List<Ts>> result = new ArrayList<List<Ts>>();
        List<Ts> subList = new ArrayList<Ts>();
        for (int i = 0; i < list.size(); i++) {
            if(i == 0){
                subList.add(list.get(0));
            }else{
                if(list.get(i).getA().equals(list.get(i - 1).getA()) && list.get(i).getB().equals(list.get(i - 1).getB())){
                    subList.add(list.get(i));
                }else{
                    result.add(subList);
                    subList = new ArrayList<Ts>();
                    subList.add(list.get(i));
                }
            }
            if(i == list.size() - 1){
                result.add(subList);
            }
        }
        return result;


test:
Java code

        List<Ts> tsList = new ArrayList<Ts>();
        tsList.add(new Ts("a", "b", "vv"));
        tsList.add(new Ts("a", "b", "@@"));
        tsList.add(new Ts("aa", "bb", "cc"));
        tsList.add(new Ts("aa", "bb", "dd"));
//        tsList.add(new Ts("ab", "ab", "@@"));
//        tsList.add(new Ts("ab", "ab", "66"));
        List<List<Ts>> result = T.getGroup(tsList);
        for (int i = 0; i < result.size(); i++) {
            List<Ts> subList = result.get(i);
            for (int j = 0; j < subList.size(); j++) {
                if ("@@".equals(subList.get(j).getC())) {
                    System.out.println(subList.get(j).toString());
                } 
                else {
                    System.out.println(subList.get(0).toString());
                }
            }
        }


输出到txt就用System.out.println代替了。。上述代码输出的是
a,b,vv
a,b,@@
aa,bb,cc
aa,bb,cc
可我想要的结果是
a,b,@@
aa,bb,cc
这个代码应该怎么改才好??急救

------解决方案--------------------
Java code

for (int i = 0; i < result.size(); i++) {
    List<Ts> subList = result.get(i);
    boolean flag = false;
    for (int j = 0; j < subList.size(); j++) {
        if ("@@".equals(subList.get(j).getC())) {
            System.out.println(subList.get(j).toString());
            flag = true;
        }
    }
    if(!flag) {
        System.out.println(subList.get(0).toString());
    }
}