Spring Boot 在Java中比较不同列表中的特定属性的最佳方法是什么?

a0zr77ik  于 2022-11-05  发布在  Spring
关注(0)|答案(1)|浏览(190)

尝试比较两个列表中的两个属性。我通常比较它迭代两个列表并比较每个元素(我认为这不是最优的)。比如:

list1.forEach(x -> {
    list2.forEach(y -> {
        if (x.getId().compareTo(y.getId()) == 0) 
            x.setMyAttribute(y.getNameAttribute());
    });
});

有没有更好的方法来比较两个列表中的特定属性?我仍然不知道如何使用HashMap,但我想知道是否使用HashMap进行比较更好,以及如何使用它。
我想我只能用idname(我需要的属性)创建一个HashMap

g2ieeal7

g2ieeal71#

您所分享的基本上是一个蛮力解决方案,它针对list1中的每个元素检查list2中的每个元素。
为了避免执行冗余的迭代,可以通过生成一个HashMap来索引list2的内容,该HashMap将一个特定的元素与它的id相关联。
我将假定id的 * 自然顺序 * 与它的equals/hashCode实现一致,即(x.compareTo(y)==0) == (x.equals(y)),因为这是推荐的做法(如果您使用id标准JDK类,如LongStringUUID,情况就是这样)。
这就是它的实现方式:

List<Foo> list1 = // initializing list1
List<Foo> list2 = // initializing list1

Map<ID, Foo> list2FoosById = list2.stream()
    .collect(Collectors.toMap(
        Foo::getId,
        Function.identity(),
        (left, right) -> right // remove merge function if IDs are expected to be unique
    ));

for (Foo x : list1) {
    Foo y = list2FoosById.get(x.getId());                  // retrieving Foo from list2 with the corresponding ID
    if (y != null) x.setMyAttribute(y.getNameAttribute()); // reassign the attribute if the Foo having identical ID exists
}

相关问题