【代码优化之路】两个不同对象集合,针对某一属性值去重。

原来的代码

 List<CategoryAttr> categoryAttrs ;
 List<GroupAttr> groupAttrs ;
 List<GroupAttr> groupAttrsNew = new ArrayList<>();
            for (GroupAttr groupAttr : groupAttrs) {
                for (CategoryAttr categoryAttr : categoryAttrs) {
                    if (categoryAttr.getAttrId().equals(groupAttr.getAttrId())) {
                        groupAttrsNew.add(groupAttr);
                    }
                }
            }
            groupAttrs.removeAll(groupAttrsNew);
        }

代码展现方式不够整洁

优化后

  List<CategoryAttr> categoryAttrs;
  List<GroupAttr> groupAttrs ;
  Set<String> categoryAttrIds = categoryAttrs.stream().map(a -> a.getAttrId()).collect(Collectors.toSet());
  List<GroupAttr> attrBos = groupAttrs.stream().filter(a -> !categoryAttrIds.contains(a.getAttrId())).collect(Collectors.toList());```
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要根据对象的某个属性一个对象集合,可以使用Java 8的Stream API和`collect()`方法结合自定义的`Collector`来实现。以下是一个示例代码: 假设有一个`Person`类,其中包含`id`和`name`两个属性: ```java import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Person> personList = new ArrayList<>(); personList.add(new Person(1, "Alice")); personList.add(new Person(2, "Bob")); personList.add(new Person(1, "Charlie")); personList.add(new Person(3, "Alice")); List<Person> distinctList = personList.stream() .collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new ArrayList<>(personList.size())), list -> list.stream().collect(Collectors.toMap( Person::getId, p -> p, (existing, duplicate) -> existing )))) .values() .stream() .collect(Collectors.toList()); distinctList.forEach(System.out::println); } } class Person { private int id; private String name; public Person(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + '}'; } } ``` 在上述示例中,我们使用了`toMap()`方法来创建一个Map,其中键是对象的某个属性(这里是`id`),对象本身。在`toMap()`方法中,我们提供了一个合并函数,以保留原始对象而不是复的对象。然后,我们通过获取Map的集合,并将其转换为List,得到了根据`id`属性对象集合。 输出结果如下: ``` Person{id=1, name='Alice'} Person{id=2, name='Bob'} Person{id=3, name='Alice'} ``` 注意,这里使用了`collectingAndThen()`方法来在收集结束后执行一些操作,即将结果转换为List。这样可以避免直接对`toMap()`的结果进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值