我有一个必须使用分隔符分割的字符串列表,然后获取分割的第二个值以创建字符串数组的映射。
这里有一个例子:
字符串列表如下:
["item1:parent1", "item2:parent1", "item3:parent2"]
应转换为具有以下条目的地图:
<key: "parent1", value: ["item1", "item2"]>,
<key: "parent2", value: ["item3"]>
我试图遵循这个问题中给出的解决方案,但没有成功
样本代码:
var x = new ArrayList<>(List.of("item1:parent1", "item2:parent1", "item3:parent2"));
var res = x.stream().map(s->s.split(":")).collect(Collectors.groupingBy(???));
假设分割数组的长度始终为2,则下面的内容应该适用于
var list = List.of("item1:parent1", "item2:parent1", "item3:parent2");
var map = list.stream()
.map(s -> s.split(":"))
.collect(Collectors.groupingBy(
s -> s[1],
Collectors.mapping(s -> s[0], Collectors.toList())));
System.out.println(map);
@厄立特里亚已经展示了如何使用流。这是另一种方式:
Map<String, List<String>> result = new LinkedHashMap<>();
x.forEach(it -> {
String[] split = it.split(":");
result.computeIfAbsent(split[1], k -> new ArrayList<>()).add(split[0]);
});
这使用了Map.computeIfAbsent
,它在这种情况下很方便。