Aje*_*mar 1 hashmap java-8 java-stream
我有如下方法
private Map<String,List<String>> createTableColumnListMap(List<Map<String,String>> nqColumnMapList){
Map<String, List<String>> targetTableColumnListMap =
nqColumnMapList.stream()
.flatMap(m -> m.entrySet().stream())
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
return targetTableColumnListMap;
}
Run Code Online (Sandbox Code Playgroud)
我想大写地图键,但找不到一种方法。有没有Java 8的方法来实现这一目标?
这不需要对收集器进行任何花哨的操作。假设您有这张地图
Map<String, Integer> imap = new HashMap<>();
imap.put("One", 1);
imap.put("Two", 2);
Run Code Online (Sandbox Code Playgroud)
只需获取的数据流,keySet()然后收集到新地图中即可,其中插入的键是大写的:
Map<String, Integer> newMap = imap.keySet().stream()
.collect(Collectors.toMap(key -> key.toUpperCase(), key -> imap.get(key)));
// ONE - 1
// TWO - 2
Run Code Online (Sandbox Code Playgroud)
编辑:
@Holger的评论是正确的,仅使用条目集会更好(更简洁),因此这是更新的解决方案
Map<String, Integer> newMap = imap.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey().toUpperCase(), entry -> entry.getValue()));
Run Code Online (Sandbox Code Playgroud)
回答您的问题[您可以复制并粘贴]:
Map<String, List<String>> targetTableColumnListMap = nqColumnMapList.stream().flatMap(m -> m.entrySet().stream())
.collect(Collectors.groupingBy(e -> e.getKey().toUpperCase(), Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9235 次 |
| 最近记录: |