list去重,分組

java8對List<Bean>進(jìn)行去重和覆蓋

不關(guān)心覆蓋邏輯,相同personId只留一條

public static List<Person> coverDuplicate(List<Person> sourceList) {
  if (CollectionUtils.isEmpty(sourceList)) {
    return new ArrayList<>();
  }
  List<Person> distinctList = sourceList.stream().collect(
    Collectors.collectingAndThen(
        Collectors.toCollection(
           () -> new TreeSet<>(Comparator.comparing(o -> o.getPersonId()))), ArrayList::new)
  );
  return distinctList;
}

相同的personId,后面的記錄要求覆蓋前面的

public static List<Person> coverDuplicate1(List<Person> sourceList) {
  if (CollectionUtils.isEmpty(sourceList)) {
    return new ArrayList<>();
  }
  List<Person> distinctList = sourceList.stream().collect(
    Collectors.toMap(Person::getPersonId, Function.identity(), (e1, e2) -> e2)
      ).values().stream().collect(Collectors.toList());
  return distinctList;
}

list string去重

1、java8

list.stream().distinct().collect(Collectors.toList());

2、借助Set的特性進(jìn)行去重,由于Set的無序性,不會保持原來順序

/**
     * 去除重復(fù)數(shù)據(jù)
     * @param list
     */
    public static List<String> list distinct(List<String> list) {
        final boolean sta = null != list && list.size() > 0;
        List doubleList= new ArrayList();
        if (sta) {
            Set set = new HashSet();
            set.addAll(list);
            doubleList.addAll(set);
        }
        return doubleList;
    }

3、利用set集合特性保持順序一致去重

// Set去重并保持原先順序的兩種方法
   public static void delRepeat(List<String> list) {
       //方法一
       List<String> listNew = new ArrayList<String>(new TreeSet<String>(list));
       //方法二
       List<String> listNew2 = new ArrayList<String>(new LinkedHashSet<String>(list));
   }

4、分組求個數(shù)

/jdk8的方法統(tǒng)計個數(shù):

Map> map = list.stream().collect(Collectors.groupingBy(User::getUserName,Collectors.counting()));

5、分組求和

studentList.stream().collect(Collectors.toMap(Student::getName, Student::getScore, Integer::sum));

List<student> studentList = new ArrayList<>();
studentList.stream()
       .collect(Collectors.groupingBy(Student::getName, Collectors.collectingAndThen(
           Collectors.summarizingDouble(Student::getScore), DoubleSummaryStatistics::getSum)));

List<student> studentList = new ArrayList<>();
studentList.stream()
       .collect(Collectors.groupingBy(Student::getName, Collectors.collectingAndThen(
            Collectors.mapping(Student::getScore, Collectors.reducing(Integer::sum)),
            Optional::get)));
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容