![](/img/trans.png)
[英]Filter Objects from two lists and do subtract with the attributes and store it in 3rd list in 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;
}
我有两个列表a
和b
。
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
。
列表a
和c
将是相同的,因为它们将包含相同的引用。 这意味着生成列表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.