英文:
Java streams for adding to a list if it exists or creating a new one in a HashMap
问题
我有一个字符串列表,必须使用分隔符进行拆分,然后获取拆分的第二个值,以创建一个字符串数组的映射。
示例:
像下面这样的字符串列表:
["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(???));
英文:
I have a list of strings that must be split using a delimiter and then get the second value of the split to create a map of string arrays.
Here is an example:
A list of strings like the following:
["item1:parent1", "item2:parent1", "item3:parent2"]
Should be converted to a map that has the following entries:
<key: "parent1", value: ["item1", "item2"]>,
<key: "parent2", value: ["item3"]>
I tried to follow the solution given in this question but with no success
Sample code:
var x = new ArrayList<>(List.of("item1:parent1", "item2:parent1", "item3:parent2"));
var res = x.stream().map(s->s.split(":")).collect(Collectors.groupingBy(???));
答案1
得分: 4
假设拆分后的数组总是长度为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);
英文:
Assuming the splited array has always a length of 2, something like below should work
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);
答案2
得分: 1
@Eritrean已经展示了如何使用流来实现。以下是另一种方法:
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
,在这种情况下非常有用。
英文:
@Eritrean has shown how to do it with streams. Here's another way:
Map<String, List<String>> result = new LinkedHashMap<>();
x.forEach(it -> {
String[] split = it.split(":");
result.computeIfAbsent(split[1], k -> new ArrayList<>()).add(split[0]);
});
This uses Map.computeIfAbsent
, which comes in handy for cases like this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论