list根据某个字段去重之后依旧返回该list

博客主要提及对list根据某个属性字段进行去重的内容,聚焦于信息技术中数据处理方面的操作。
Map<Object, Boolean> map = new HashMap<>();
            dtoList = dtoList.stream().filter(i -> map.putIfAbsent(i.getCompanyName(), Boolean.TRUE) == null).collect(Collectors.toList());

list根据某个属性字段做去重

List<Entity> distinctList = list.stream()
                                .distinct()
                                .collect(Collectors.collectingAndThen(
                                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Entity::getProperty))),
                                    ArrayList::new));

在Java中,可以使用`Stream`的`distinct()`方法结合自定义的`equals()`和`hashCode()`方法来实现根据某个字段。以下是示例代码: ```java import java.util.*; import java.util.stream.Collectors; class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return Objects.equals(name, person.name); // 根据name字段 } @Override public int hashCode() { return Objects.hash(name); // 根据name字段生成hashCode } } public class Main { public static void main(String[] args) { List<Person> list = Arrays.asList( new Person("Alice", 25), new Person("Bob", 30), new Person("Alice", 28) // 复的name ); List<Person> distinctList = list.stream() .distinct() .collect(Collectors.toList()); distinctList.forEach(p -> System.out.println(p.getName() + " " + p.getAge())); } } ``` 输出结果: ``` Alice 25 Bob 30 ``` ### 替代方案(使用`TreeSet`或自定义比较器) 如果不想修改`equals()`和`hashCode()`,可以使用`TreeSet`或`Collectors.toCollection()`配合自定义比较器: ```java List<Person> distinctList = list.stream() .collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new )); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值