在Java 8中,如何将两个不同的集合合并为一个匹配的字段?

时间:2016-05-25 02:55:01

标签: java java-8 java-stream

我想使用一个匹配字段组合2个不同的数据类型集合。

List<Foo> foos...
List<Bar> bars... 

public class Foo {
    Integer fooId;
    Integer name;
    Integer description;
    Integer sent; //this should be coming from Bar
    Integer received; //this should be coming from Bar
}

public class Bar {
    Integer barId;
    Integer fooId; //combine into Foo using this field
    Integer sent;
    Integer received;
}

我想从Bar获取数据,然后使用fooId将它们放入Foo。两个集合都有fooId的唯一数据。

4 个答案:

答案 0 :(得分:1)

为了让代码更漂亮,你可以看看下面这个:)

node_modules

List<Foo> foos = ... List<Bar> bars = ... // convert list bars to the map Map<Integer, Bar> map4Bar = bars.stream().collect(Collectors.toMap(Bar::getFooId, Function.identity())); // combine the some bar into the foo foos.forEach(foo -> foo.modifyByBar(map4Bar.get(foo.getFooId()))); 类中应该有一个名为convert的新方法,就像这样:

Foo

我的代码更漂亮了吗?也许......不,哈哈~~~ ^ _ ^

答案 1 :(得分:0)

尝试迭代每个元素组合并检查是否foos[index].fooId == bars[index2].fooId。像这样:

for(Foo foo : foos){
   for(Bar bar : bars){
      if(foo.fooId == bar.fooId){
         foo.sent = bar.sent;
         foo.received = bar.received;
      }
   }
}

答案 2 :(得分:0)

Stream<Foo> fooStream = foos.stream();
fooStream.forEach(f ->
    bars.stream().filter(b -> b.fooId.equals(f.fooId)).findFirst().ifPresent(b -> {
      f.sent = b.sent;
      f.received = b.received;
    })
);

答案 3 :(得分:0)

您有一个经典的查找问题,因此我建议您将其作为查找处理:

    List<Foo> foos = ...
    List<Bar> bars = ...

    Map<Integer, Bar> barLookup = bars.stream().collect(Collectors.toMap(bar -> bar.fooId, bar -> bar));
    foos.forEach(foo -> {
        Bar bar = barLookup.get(foo.fooId);
        foo.sent = bar.sent;
        // etc
    });