[英]How to Get common Items from a stream of objects in Java8
我有2个Coll对象流,我想根据实例变量在这里说i
的一个来找到公共对象。 我需要使用Java 8流来执行此操作。 此外,我需要通过对公共元素乘以1000的乘数来更新j
变量。
class Coll
{
Integer i;
Integer j;
public Coll(Integer i, Integer j) {
this.i = i;
this.j = j;
}
public Integer getI() {
return i;
}
public void setI(Integer i) {
this.i = i;
}
public Integer getJ() {
return j;
}
public void setJ(Integer j) {
this.j = j;
}
}
我在拧类似的东西:
public static void main(String args[])
{
Stream<Coll> stream1 = Stream.of(new Coll(1,10),new Coll(2,20),new Coll(3,30) );
Stream<Coll> stream2 = Stream.of(new Coll(2,20),new Coll(3,30),new Coll(4,40) );
Stream<Coll> common = stream1
.filter(stream2
.map(x->x.getI())
.collect(Collectors.toList())
::equals(stream2
.map(x->x.getI()))
.collect(Collectors.toList()));
common.forEach( x-> x.setJ(x.getJ()*1000));
common.forEach(x -> System.out.println(x));
}
我在做等于方法时出错了!! 我猜Java8不支持带有equals参数的方法!
我收到编译错误: expected a ')' or ';'
约等于法
将逻辑移到外部收集Stream2的所有i
。 然后如果其他列表中存在i
则过滤stream1中的所有Coll
。
List<Integer> secondCollStreamI = stream2
.map(Coll::getI)
.collect(Collectors.toList());
Stream<Coll> common = stream1
.filter(coll -> secondCollStreamI.contains(coll.getI()));
common.forEach( x-> x.setJ(x.getJ()*1000));
common.forEach(x -> System.out.println(x));
由于您无法重用该流,因此最后一条语句将导致IllegalStateException
( stream has already been operated upon or closed
)。 您需要在某个地方将其收集到List<Coll>
...类似...
List<Coll> common = stream1
.filter(coll -> secondCollStreamI.contains(coll.getI()))
.collect(Collectors.toList());
common.forEach(x -> x.setJ(x.getJ() * 1000));
common.forEach(System.out::println);
或者,如果您想在不收集的情况下即时进行所有操作
stream1
.filter(coll -> secondCollStreamI.contains(coll.getI()))
.forEach(x-> {
x.setJ(x.getJ()*1000);
System.out.println(x);
});
你可以这样做
Map<Integer, Coll> colsByI = listTwo.stream()
.collect(Collectors.toMap(Coll::getI, Function.identity()));
List<Coll> commonElements = listOne.stream()
.filter(c -> Objects.nonNull(colsByI.get(c.getI())) && c.getI().equals(colsByI.get(c.getI()).getI()))
.map(c -> new Coll(c.getI(), c.getJ() * 1000))
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.