2016-04-14 24 views
1

我来到一个跨我没问题;吨设法解决...加入2种不同对象的列表使用Java 8第三对象的列表流

我有3种类型的对象

  1. MyObject1 - 带有字段ID和名称
  2. MyObject2 - 带有字段ID和错误
  3. MyJoinObject - 带有字段ID,名称和错误

我有2所列出:

  1. MyObject1
  2. MyObject2

的名单列表我要创建MyJoinObject,这是一个加入2所列出的第三列表。 将MyJoinObject对象作为MyObject1对象,但如果存在(由id加入),它们也将包含错误。 我想要这样做与Java 8流

+5

如果你给[mcve]包括你到目前为止尝试过的东西,这将会非常有帮助。如果单个MyObject1有多个错误会发生什么? –

+0

每个对象列表都包含一个由id属性组成的唯一对象,因此对象可以有一个或一个错误。 – SharonBL

+2

嗯。在LINQ(.NET)中,这将是微不足道的。不幸的是,我不确定在Java流中进行组连接的等价物。我仍然强烈建议你用[mcve]更新你的问题,这将使人们更容易帮助你。包括示例输入数据(硬编码)和预期输出数据......以及您已经尝试过的任何内容。 –

回答

1

你可以做这样的事情:

List<MyJoinObject> result = 
    list1.stream().map(o1 -> { 
     Optional<MyObject2> error = list2.steam() 
             .filter(o2 -> o2.getId() == o1.getId()) 
             .findAny(); 
     if (error.isPresent()) 
      return new MyJoinObject(o1.getId(), o1.getName(), error.get().getError());  

     return new MyJoinObject(o1.getId(), o1.getName()); 

    }).collect(Collectors.toList()); 

您也可以通过做构建在做之前ID映射错误的hasmap:

final Map<Integer, MyObject2> errorsById = 
    list2.stream() 
      .collect(Collectors.toMap(MyObject2::getId, Function.identity())); 

如果你这样做,你可以使用这张地图通过调用方法containsKey()get()来检索错误

1

像这样的东西可以工作(虽然我没有验证):

public static void main(String[] args) { 
    List<MyObject1> object1list = new ArrayList<>(); // fill with data 
    List<MyObject2> object2list = new ArrayList<>();// fill with data 

    List<MyJoinObject> joinobjectlist = new ArrayList<>(); 

    object1list.stream().forEach(
      o1 -> object2list.stream().filter(
        o2-> o1.getId()==o2.getId() 
        ).forEach(o2->joinobjectlist.add(
          new JoinObject(o2.getId(), o1.getName(), o2.getError())) 
          ) 
      ); 

} 
1

为了您的信息:

public static void main(String[] args) { 

    List<MyObject1> myObject1s = new ArrayList<>(); 
    List<MyObject2> myObject2s = new ArrayList<>(); 

    // convert myObject2s to a map, it's convenient for the stream 
    Map<Integer, MyObject2> map = myObject2s.stream().collect(Collectors.toMap(MyObject2::getId, Function.identity())); 

    List<MyJoinObject> myJoinObjects = myObject1s.stream() 
               .map(myObject1 -> new MyJoinObject(myObject1, map.get(myObject1.getId()).getError())) 
               .collect(Collectors.toList()); 

} 

当然,应该有MyJoinObject一个新的建筑,就像这样:

public MyJoinObject(MyObject1 myObject1, String error){ 
    this.id = myObject1.getId(); 
    this.name = myObject1.getName(); 
    this.error = error; 
} 

这就是全部。 :P