[英]Create a map from two different lists based on common conditions using Java 8 Streams
[英]Java streams, create new object based on two different objects
基于两个不同对象创建新对象的最佳方法是什么。
我想使用Java流。
我的两个开始对象
public class EventA{
Long id;
String name;
...
Long locationID;
}
public class EventB{
Long id
String Name;
...
Long locationID;
}
我的成绩课
public class Result{
Long locationID;
String eventAName;
String eventBName;
public Result(...){...}
}
我有两个像这样的对象数组
List<EventA> eventAList;
List<EventB> eventBList;
我喜欢获取一个Result对象数组。 每个EventA名称都应复制到resultList。 如果在相同位置存在一个EventB ,我想将该名称保存在eventBName中 。
到目前为止,我所做的就是
List<Result> resultList = eventAList.stream().map(e -> new Result(e.locationID, e.name, null)).collect(Collectors.toList());
我不知道如何将值从EventB传递给构造函数
创建Result
,可以使用流对eventBList
的值进行迭代,以仅保留与eventAList
值具有相同locationID
的值,然后采用找到的值,并将其map()
为它的Name
值,或者为null
如果不存在:
List<Result> resultList = eventAList.stream().map(a -> new Result(a.locationID, a.name,
eventBList.stream().filter(b -> b.locationID.equals(a.locationID)).findAny().map(b -> b.Name).orElse(null)
)).collect(Collectors.toList());
为了获得更好的性能,您可以使用一个临时Map
:
final Map<Long, String> eventBMap = eventBList.stream().collect(Collectors.toMap(b -> b.locationID, b -> b.Name));
List<Result> resultList = eventAList.stream().map(a -> new Result(a.locationID, a.name,
eventBMap.get(a.locationID)
)).collect(Collectors.toList());
我找到了一种工作方法
我将Result类的构造函数调整为
public Result(Long locationID, String eventAName, EventB eventB){
this.locationID = locationID;
this.eventAName = eventAName;
this.eventBName = eventB.name;
}
然后在我的java流中
List<Result> resultList = eventAList.stream().map(ea -> new Result(ea.locationID, ea.name, eventBList.stream().filter(eb -> eb.locationID.equals(ea.locationID)).findFirst().orElse(new EventB()).get()).collect(Collectors.toList());
您可以执行以下操作,然后进行增强(例如,以locationId为键为eventBlist创建地图,以加快搜索速度)
Function<EventA, SimpleEntry<EventA, Optional<EventB>>> mapToSimpleEntry = eventA -> new SimpleEntry<>(eventA,
eventBList.stream()
.filter(e -> Objects.equals(e.getLocationID(), eventA.getLocationID()))
.findFirst());
Function<SimpleEntry<EventA, Optional<EventB>>, Result> mapToResult = simpleEntry -> {
EventA eventA = simpleEntry.getKey();
Optional<EventB> eventB = simpleEntry.getValue();
return new Result(eventA.getLocationID(), eventA.getName(), eventB.map(EventB::getName).orElse(null));
};
eventAList.stream()
.map(mapToSimpleEntry)
.map(mapToResult)
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.