[英]Java streams: collect to map creating two keys for each stream element
I have a Java stream that invokes .collect(Collectors.toMap)
.我有一个调用
.collect(Collectors.toMap)
的 Java 流。 Collectors.toMap
accepts a keyMapper
and a valueMapper
functions. Collectors.toMap
接受一个keyMapper
和一个valueMapper
函数。 I'd like to create two entries for each stream element, with two different keyMapper
functions, but with the same valueMapper
function.我想为每个流元素创建两个条目,使用两个不同的
keyMapper
函数,但使用相同的valueMapper
函数。 Is it possible to do this in a nice stream syntax without creating a custom collector?是否可以在不创建自定义收集器的情况下以良好的流语法执行此操作?
Of course, I could also get one map, then add another set of keys with the same values to it, outside of the stream chain calls.当然,我也可以得到一个映射,然后在流链调用之外添加另一组具有相同值的键。 But I was wondering if it could be made neater...
但我想知道它是否可以做得更整洁......
Basically what I have is:基本上我所拥有的是:
List<A> someObjects = ...; // obtain somehow
Map<String, B> res = someObjects.stream().collect(Collectors.toMap(keyMapper1, valueMapper));
And functions keyMapper1
and keyMapper2
produce different strings, and I want both of those in my map with the same value.并且函数
keyMapper1
和keyMapper2
产生不同的字符串,我希望我的地图中的这两个具有相同的值。
What I can do is:我能做的是:
Map<A, B> map = someObjects.stream().collect(Collectors.toMap(Function.identity(), valueMapper));
Map<String, B> result = new HashMap<>();
map.forEach((a, b) -> {
result.put(keyMapper1(a), b);
result.put(keyMapper2(a), b);
});
But maybe something could be done without creating an intermediate variable?但是也许可以在不创建中间变量的情况下完成某些事情?
You can use flatMap
to create a stream of all the map entries first, and then collect them to a map.您可以使用
flatMap
首先创建所有地图条目的流,然后将它们收集到地图中。 Something like this:像这样的东西:
Map<String, String> map = someObjects.stream()
.flatMap(obj -> Stream.of(
Map.entry(keyMapper1(obj), valueMapper(obj)),
Map.entry(keyMapper2(obj), valueMapper(obj))))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.