来自以下输入
-e equivalent to -vE
-E, --show-ends
display $ at end of each line
-v, --show-nonprinting
use ^ and M- notation, except for LFD and TAB
如何获得以下输出
[
[{group=a, value=cat}, {group=b, value=dog}],
[{group=a, value=cow}, {group=b, value=bat}]
]
使用Java 8流?
我有以下标准解决方案
{
a=[{value=cat}, {value=cow}],
b=[{value=dog}, {value=bat}]
}
我看到有Collectors.groupingBy
方法,但我无法弄清楚如何使用它。
Map<String, String > map1 = new LinkedHashMap<>();
map1.put("group", "a");
map1.put("value", "cat");
Map<String, String > map2 = new LinkedHashMap<>();
map2.put("group", "b");
map2.put("value", "dog");
Map<String, String > map3 = new LinkedHashMap<>();
map3.put("group", "a");
map3.put("value", "cow");
Map<String, String > map4 = new LinkedHashMap<>();
map4.put("group", "b");
map4.put("value", "bat");
List<Map<String, String>> list1 = Arrays.asList(map1, map2);
List<Map<String, String>> list2 = Arrays.asList(map3, map4);
List<List<Map<String, String>>> input = Arrays.asList(list1, list2);
Map<String, List<Map<String, String>>> output = new LinkedHashMap<>();
for (List<Map<String, String>> list : input) {
for (Map<String, String> map : list) {
String group = map.get("group");
if (!output.containsKey(group)) {
output.put(group, new ArrayList<>());
}
List<Map<String, String>> values = output.get(group);
values.add(map);
}
}
答案 0 :(得分:7)
要生成相同的输出,您应该在分组之前通过flatMap
将列表列表展平到单个列表中:
output = input.stream().flatMap(List::stream)
.collect(Collectors.groupingBy(map -> map.get("group")));
此代码生成与您发布的命令性代码相同的输出:
{
a=[{group=a, value=cat}, {group=a, value=cow}],
b=[{group=b, value=dog}, {group=b, value=bat}]
}
但请注意,它与您想要的输出不同。要获得所需的输出,您可能需要指定下游收集器:
output = input.stream()
.flatMap(List::stream)
.collect(Collectors.groupingBy(map -> map.get("group"),
Collectors.mapping(
map -> Collections.singletonMap("value", map.get("value")),
Collectors.toList())));
现在结果是
{
a=[{value=cat}, {value=cow}],
b=[{value=dog}, {value=bat}]
}