[英]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.