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)));