一、去除List中重复的String

List 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 unique = persons.stream().collect(

                collectingAndThen(

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

        );