如何从 Java8 中的对象流中获取公共项

我有 2 个 Coll 对象流,我想根据实例变量i在这里说的一个来查找公共对象。我需要使用 Java 8 流来做到这一点。此外,我需要j通过对公共元素乘以 1000来更新变量。


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 这样的带参数的方法!!


我收到一个编译错误:expected a ')' or ';'围绕 equals 方法


慕丝7291255
浏览 203回答 2
2回答

慕尼黑的夜晚无繁华

你可以这样做,Map<Integer, Coll> colsByI = listTwo.stream()&nbsp; &nbsp; .collect(Collectors.toMap(Coll::getI, Function.identity()));List<Coll> commonElements = listOne.stream()&nbsp; &nbsp; .filter(c -> Objects.nonNull(colsByI.get(c.getI())) && c.getI().equals(colsByI.get(c.getI()).getI()))&nbsp; &nbsp; .map(c -> new Coll(c.getI(), c.getJ() * 1000))&nbsp; &nbsp; .collect(Collectors.toList());

开满天机

将逻辑移到i外面收集Stream2 的所有内容。然后过滤流1中的所有内容Coll,如果它i存在于另一个列表中。List<Integer> secondCollStreamI = stream2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(Coll::getI)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());Stream<Coll> common = stream1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .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&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(coll -> secondCollStreamI.contains(coll.getI()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());common.forEach(x -> x.setJ(x.getJ() * 1000));common.forEach(System.out::println);或者,如果您想在不收集的情况下即时完成所有操作stream1&nbsp; &nbsp; &nbsp; &nbsp; .filter(coll -> secondCollStreamI.contains(coll.getI()))&nbsp; &nbsp; &nbsp; &nbsp; .forEach(x->&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x.setJ(x.getJ()*1000);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(x);&nbsp; &nbsp; &nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java