完美解决Java中List集合去除重复的JavaBean对象某些属性值方案

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/codekxx/article/details/53516577

最近在写安卓的一个筛选功能,由于后台没有给接口,所以要把服务器返回搜索结果的数据进行分组。但是又有重复的属性,要把它们全部剔除。

部分JSON数据如下:

"items": [
    {
      "class_id": "72",
      "brand_id": "2",
      "brand_name": "隆力奇",
      "class_name": "洗发护发、身体护肤",
    },
    {
      "class_id": "73",
      "brand_id": "2",
      "brand_name": "隆力奇",
      "class_name": "保健食品、滋补养生",
    },
    {
      "class_id": "75",
      "brand_id": "3",
      "brand_name": "呵呵哒",
      "class_name": "保健食品、滋补养生",
    },
    {
      "class_id": "52",
      "brand_id": "2",
      "brand_name": "隆力奇",
      "class_name": "美容护肤、面膜、爽肤水",
    },
    {
      "class_id": "53",
      "brand_id": "2",
      "brand_name": "隆力奇",
      "class_name": "美容护肤、面膜、爽肤水",
    },
    {
      "class_id": "51",
      "brand_id": "2",
      "brand_name": "隆力奇",
      "class_name": "美容护肤、面膜、爽肤水",
    },
    {
      "class_id": "57",
      "brand_id": "2",
      "brand_name": "隆力奇",
      "class_name": "男士护理、洗面奶",
    },
  ]

需要去重部分:

这里写图片描述

JavaBean如下:

/**
 * 筛选bean
 * Created by kxx on 2016/12/8.
 */

public class FilterBean {
    public int id;

    public String name;


    public FilterBean(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public FilterBean(){}
}

把所有数据存在一个集合里面List<FilterBean> brandList


关键步骤:

for (int i = 0; i < brandList.size()-1; i++) {
            for (int j = brandList.size()-1; j > i; j--) {
                if (brandList.get(j).id == brandList.get(i).id) {
                    brandList.remove(j);
                }
            }
        }

打印结果如下:

for (FilterBean s:brandList){
   Log.d("搜索品牌",s.name);
}
12-08 11:41:50.782 29877-29877/com.*** D/搜索品牌: 隆力奇
12-08 11:41:50.782 29877-29877/com.*** D/搜索品牌: 呵呵哒

成功去重!!!


番外篇:

第一种:如果想要集合中的元素不会有重复,那么推荐使用hashSet,如下:

//  list是有重复元素的List 集合 
    HashSet hs  =   new  HashSet(list);  
    list.clear();  
    list.addAll(hs); 

第二种:去重String集合工具类

    /**
     * String集合去重
     * @param li
     * @return
     */
    public static List<String> getNewList(List<String> li){
        List<String> list = new ArrayList<String>();
        for(int i=0; i<li.size(); i++){
            String str = li.get(i);  //获取传入集合对象的每一个元素
            if(!list.contains(str)){   //查看新集合中是否有指定的元素,如果没有则加入
                list.add(str);
            }
        }
        return list;
    }

方法还有有很多种……and so on……

猜你喜欢

转载自blog.csdn.net/codekxx/article/details/53516577