我有 2 个 Coll 对象流,我想根据实例变量 i
找到公共(public)对象。我需要使用 Java 8 流来执行此操作。
此外,我需要通过公共(public)元素的乘数 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));
}
我在 equals 方法周围做错了什么!!我猜Java8不支持像equals这样带有参数的方法!!
我收到编译错误:在 equals 方法周围需要一个“)”或“;”
最佳答案
你可以这样做,
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());
关于java - 如何从 Java8 中的对象流中获取公共(public)项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51759200/