JDK1.8 去除重複

一、去除List中重複的String

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


二、List中對象去重

public class Person {

    private Long id;


    private String name;


    public Person(Long id, String name) {

        this.id = id;

        this.name = name;

    }


    public Long getId() {

        return id;

    }


    public void setId(Long id) {

        this.id = id;

    }


    public String getName() {

        return name;

    }


    public void setName(String name) {

        this.name = name;

    }


    @Override

    public String toString() {

        return "Person{" +

                "id=" + id +

                ", name='" + name + '\'' +

                '}';

    }

}


import static java.util.Comparator.comparingLong;

import static java.util.stream.Collectors.collectingAndThen;

import static java.util.stream.Collectors.toCollection;


// 根據id去重

     List<Person> unique = persons.stream().collect(

                collectingAndThen(

                        toCollection(() -> new TreeSet<>(comparingLong(Person::getId))), ArrayList::new)

        );


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章