cbm*_*m64 5 java hashmap inverse java-8
我想改变一个,Map<String, List<Object>>所以它变成了Map<String, String>.如果它只是Map<String, Object>在Java8中很容易;
stream().collect(k -> k.getValue().getMyKey(), Entry::getKey);
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为getValue Map<List<Object>, String>在我的示例中返回一个List .假设Object包含一个用于键的getter,Object并且不包含第一个map中的键.
有什么想法吗?
流式传输对象列表并提取所需的密钥map--> flatten-->toMap
source.entrySet()
.stream()
.flatMap(e -> e.getValue()
.stream()
.map(x -> new SimpleEntry<>(x.getMyKey(), e.getKey())))
.collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));
Run Code Online (Sandbox Code Playgroud)
如果预计会有重复getMyKey()值,请使用合并函数:
source.entrySet()
.stream()
.flatMap(e -> e.getValue()
.stream()
.map(x -> new SimpleEntry<>(x.getMyKey(), e.getKey())))
.collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue, (l, r) -> l));
Run Code Online (Sandbox Code Playgroud)
注意:上面使用源映射键作为结果映射的值,就像您在帖子中所说明的那样,但是如果您希望源映射的键保留为结果映射的键,则更new SimpleEntry<>(x.getMyKey(), e.getKey())改为new SimpleEntry<>(e.getKey(),x.getMyKey())。
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |