繁体   English   中英

从两个列表中过滤具有相同属性的对象并更新它们并将其存储在 Java 8 中的第三个列表中

[英]Filter Objects having the same property from two Lists and Update them and Store it in a 3rd List in Java 8

我有以下 class:

@AllArgsConstructor
@Getter
@Setter
public static class Manipulate {
    private int id;
    private int quantity;
}

我有两个列表ab

List<Manipulate> a = new ArrayList<>();
a.add(new Manipulate(1,100));
a.add(new Manipulate(2,200));

List<Manipulate> b = new ArrayList<>();
b.add(new Manipulate(1,10));
b.add(new Manipulate(2,20));

我需要根据id属性过滤这两个列表。

我想从 a 中包含的对象数量中减去b中包含a对象数量,并将结果存储到List中。

我的尝试:

List<Manipulate> c = a.stream().map(k -> {
    b.stream().filter(j -> j.getId() == k.getId())
        .forEach(i -> {
            int i1 = k.getQuantity() - i.getQuantity();
            k.setQuantity(i1);
        });
    return k;
});

我收到以下编译错误:

Required type: List <Manipulate> Provided: Stream<Object>
no instance(s) of type variable(s) R exist so that Stream<R> conforms to List<Manipulate>

您的代码有几个问题:

  • map()是一个中间操作,这意味着它不会产生结果值,而是返回另一个 stream。 为了从 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 产生结果,您需要应用终端操作(例如collect()reduce()findFirst() )。 有关详细信息,请参阅API 文档

  • 函数式编程中,对传递给function的 arguments 进行变异并不是一个好习惯(这就是您在map()中所做的事情)。

  • 您的代码基于蛮力逻辑(这总是暗示可能的最差性能):对于a中的每个元素,迭代b中的所有元素。 相反,我们可以通过将列表b中存在的所有id放入基于哈希的集合中来索引它们(这将允许在恒定时间内找出特定id是否存在于b中)并将每个id与对应quantity 即我们可以生成HashMap ,将b中的每个id映射到它的quantity

  • 列表ac将是相同的,因为它们将包含相同的引用。 这意味着生成列表c没有意义的,除非您希望它包含具有列表b中存在的id的元素。

这就是您的代码可能被重新实现的方式:

List<Manipulate> a = // initializing list a
List<Manipulate> b = // initializing list b

// mapping each `id` in the `b` to it's `quantity`

Map<Integer, Integer> quantityById = b.stream()
    .collect(Collectors.toMap(
        Manipulate::getId,      // keyMapper
        Manipulate::getQuantity // valueMapper
    ));

// generating the list `c`, containing only elements
// with `id` that are present in the `b`
        
List<Manipulate> c = a.stream()
    .filter(m -> quantityById.containsKey(m.getId()))
    .collect(Collectors.toList()); // or .toList() for Java 16+

// updating `quantity` property of each element in `c`
    
for (Manipulate m : c)
    m.setQuantity(
        m.getQuantity() - quantityById.get(m.getId())
    );

如果您不打算更改a中的数据,那么您需要为每个匹配的id创建新的Manipulate实例。 在 stream 中做这件事完全没问题:

List<Manipulate> a = // initializing list a
List<Manipulate> b = // initializing list b
Map<Integer, Integer> quantityById = // generate a map like shown above

List<Manipulate> c = a.stream()
    .filter(m -> quantityById.containsKey(m.getId()))
    .map(m -> new Manipulate(m.getId(), m.getQuantity() - quantityById.get(m.getId())))
    .collect(Collectors.toList()); // or .toList() for Java 16+

注意:您需要将第三个参数添加到Collectors.toMap()以防列表b中可能存在重复的id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM