0
点赞
收藏
分享

微信扫一扫

[黑手]使用jdk8特性,实现列表对象同属性去重

山竹山竹px 2022-02-16 阅读 33
java

实体类

public class Person {
    private String id;
    private String name;
 
    public Person(String id, String name) {
        this.id = id;
        this.name = name;
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }

根据实体类的id属性去重

public class MainTest {
    public static void main(String[] args) {
        List<Person> list = new ArrayList<Person>();
        Person p1 = new Person("1", "123");
        Person p2 = new Person("2", "123");
        Person p3 = new Person("1", "456");
        list.add(p1);
        list.add(p2);
        list.add(p3);
 
        List<Person> result = list.stream().collect(
        	Collectors.collectingAndThen(
        		Collectors.toCollection(
        			() -> new TreeSet<Person>(Comparator.comparing(p -> p.getId()))),ArrayList::new));
 
        for (Person person : result) {
            System.out.println(person.getId() + " " + person.getName());
        }
    }
}
举报

相关推荐

0 条评论