List 如何根据对象的属性去重

1.字符串去重
普通写法

    private static List<String> removeStringListDupli(List<String> stringList) {
        Set<String> set = new LinkedHashSet<>();
        set.addAll(stringList);
        stringList.clear();
        stringList.addAll(set);
        return stringList;
    }

使用Java8的写法:

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

二、List中对象去重
必须重写Person对象的equals()方法和hashCode().

public class Person {
    private Long id;
    
    private String name;
    
    public Person(Long id, String name) {
        this.id = id;
        this.name = name;
    }
    
    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Person person = (Person) o;
        if (!id.equals(person.id)) {
            return false;
        }
        return name.equals(person.name);
        
    }
    
    @Override
    public int hashCode() {
        int result = id.hashCode();
        result = 31 * result + name.hashCode();
        return result;
    }
}
    Person p1 = new Person(1L, "jack");
        Person p2 = new Person(3L, "jack chou");
        Person p3 = new Person(2L, "tom");
        Person p4 = new Person(4L, "hanson");
        Person p5 = new Person(5L, "胶布虫");
    
        List<Person> persons = Arrays.asList(p1, p2, p3, p4, p5, p5, p1, p2, p2);
    
        List<Person> personList = new ArrayList<>();
        // 去重
        persons.stream().forEach(
                p -> {
                    if (!personList.contains(p)) {
                        personList.add(p);
                    }
                }
        );
        System.out.println(personList);

三、根据Person对象的某个属性去重

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
import static java.util.Comparator.comparingLong;

 // 去重
List<Person> unique = persons.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparingLong(Person::getId))), ArrayList::new)
);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值