天天看点

Java8 新特性 stream 指定某一个属性值去重和数据集合去重

一、根据对象中的某一个或多个属性去重

 a、根据CellPhone去重

List<StaffDTO> dataList = listData.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                    new TreeSet<>(Comparator.comparing(StaffDTO::getCellPhone))), ArrayList::new));
           

 b、根据Name,CellPhone两个属性去重

List<StaffDTO> unique = persons.stream().collect(
           Collectors. collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getCellPhone()))), ArrayList::new)
);
           

二、根据集合中的重复数据去重

List<StaffDTO> dataList = listData.stream().distinct().collect(Collectors.toList());