这里我将两个不同的列表转换为单个地图。在我使用normal for循环之前做这个。现在我因为性能问题而使用流。在使用流时,如何为对象列表使用相同的mapObject。
final Set<Object1> objects1 = new HashSet<Object1>();
final Set<Object2> objects2 = new HashSet<Object2>();
final Map<Id, Object> objectMap = new HashMap<Id, Object>();
private void addObjectsToMap(Map<Id, Object> objectMap, final Collection<? extends Object> objects)
{
// used this operation earlier to convert
for (final Object object : objects)
{
objectMap.put(object.getId(), object);
}
// using this one now
objectMap = objects.parallelStream().collect(
Collectors.toMap(object -> object.getId(), object -> object));
}
addObjectsToMap(objectMap, objects1);
addObjectsToMap(objectMap, objects2);
答案 0 :(得分:3)
您可以使用Stream&#39; s concat
将2个流连接到单个流中Map<Integer, Object> objectMap;
objectMap = Stream.concat(objects1.stream(), objects2.stream())
.parallel()
.collect(Collectors.toMap(Object::getId, Function.identity()));