集合去重,根据元素中某个字段去重

1、流过滤(推荐)
                    //AppIspArea::getRegionCode是键映射函数,它告诉toMap收集器使用RegionCode字段作为键。Function.identity()是值映射函数,它表示值就是条目本身。
                    // 最后的lambda表达式(existing, replacement) -> existing定义了当键冲突时如何解决,此例中选择保留现有的条目。
                    List<AppIspArea> distinctFinalList = finalList.stream().collect(Collectors.toMap(AppIspArea::getRegionCode, Function.identity(),
                            (existing, replacement) -> existing )).values().stream().collect(Collectors.toList());

 


2、LinkedHashSet去重

List<String> list = new ArrayList<>();
list.add("111");
list.add("22");
list.add("111");
list.add("33");
list.add("111");
List<String> newPhoneList = new ArrayList<String>(new LinkedHashSet<>(list));//LinkedHashSet集合去重
  

 

3、stream去重

 //添加信息
    List<PenBean> penBeanList = new ArrayList<PenBean>();
    penBeanList.add(new PenBean("铅笔","black"));
    penBeanList.add(new PenBean("铅笔","white"));
    penBeanList.add(new PenBean("铅笔","black"));
    penBeanList.add(new PenBean("中性笔","white"));
    penBeanList.add(new PenBean("中性笔","white"));
 
    //使用java8新特性stream进行List去重
    List<PenBean> newPenBeanList = penBeanList.stream().distinct().collect(Collectors.toList());

 

4、Hashset去重

 //添加信息
    List<PenBean> penBeanList = new ArrayList<PenBean>();
    penBeanList.add(new PenBean("铅笔","black"));
    penBeanList.add(new PenBean("铅笔","white"));
    penBeanList.add(new PenBean("铅笔","black"));
    penBeanList.add(new PenBean("中性笔","white"));
    penBeanList.add(new PenBean("中性笔","white"));
 
    //新数据
    List<PenBean> newPenBeanList = new ArrayList<PenBean>();
    //set去重
    HashSet<PenBean> set = new HashSet<>(penBeanList);
    newPenBeanList.addAll(set);

 

posted on 2023-02-16 08:34  五官一体即忢  阅读(17)  评论(0编辑  收藏  举报

导航