1. 程式人生 > >使用 Java8的 stream對list資料去重

使用 Java8的 stream對list資料去重

list去重,根據物件某個屬性、某幾個屬性去重

去除List中重複的String

List unique = list.stream().distinct().collect(Collectors.toList());

去除List中重複的物件

// Person 物件
public class Person {
    private String id;

    private String name;

    private String sex;

    <!--省略 get set-->
}
// 根據name去重
List<Person> unique = persons.stream().collect(
            collectingAndThen(
                    toCollection(() -> new
TreeSet<>(comparing(Person::getName)))
, ArrayList::new) );
// 根據name,sex兩個屬性去重
List<Person> unique = persons.stream().collect(
            collectingAndThen(
                    toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList
::new) );