![](/img/trans.png)
[英]Java Streams: Create Map Using Multiple List of different object types
[英]Join list of 2 different object to a list of a third object using Java 8 streams
我遇到了一個問題,我沒有解決問題......
我有3種類型的對象
我有2個清單:
我想創建MyJoinObject的第三個列表,它是2個列表的連接。 將MyJoinObject對象作為MyObject1對象,但如果存在,它們也將包含錯誤(由id加入)。 我想用Java 8流做到這一點。
你可以這樣做:
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( )
來檢索錯誤來使用此映射
這樣的東西可以工作(雖然我沒有驗證):
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()))
)
);
}
供你參考:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.