我想转换一个2D列表,如下所示:
["A", "1"]
["B", "2"]
["A", "3"]
["A", "4"]
["A", "7"]
["B", "3"]
["B", "1"]
我想转换这个列表使用流API如下:
["A", ["1", "3", "4", "7"]]
["B", ["2", "3", "1"]]
我该怎么做?
这里有一种方法。
- 流式传输列表
- 按每个列表中的第一个元素分组
List<List<String>> lists =List.of(List.of("A", "1"),
List.of("B", "2"),
List.of("A", "3"),
List.of("A", "4"),
List.of("A", "7"),
List.of("B", "3"),
List.of("B", "1"));
Map<String,List<String>> map =
lists.stream().collect(Collectors.groupingBy(lst->lst.get(0),
Collectors.mapping(lst->lst.get(1),
Collectors.toList())));
打印
A=[1, 3, 4, 7]
B=[2, 3, 1]
这个怎么样:
var input = List.of(
List.of("A", "1"),
List.of("B", "2"),
List.of("A", "3"),
List.of("A", "4"),
List.of("A", "7"),
List.of("B", "3"),
List.of("B", "1"));
var output = input.stream()
.collect(Collectors.groupingBy(list -> list.get(0), Collectors.mapping(list -> list.get(1), Collectors.toList())));
System.out.println(output);
结果是:
{A=[1, 3, 4, 7], B=[2, 3, 1]}
下面的答案不使用stream
API。但是,知道更多的方法是件好事
Java 8在Map
中添加了一个新方法来帮助处理这种情况:
List<List<String>> input = List.of(
List.of("A", "1"),
List.of("B", "2"),
List.of("A", "3"),
List.of("A", "4"),
List.of("A", "7"),
List.of("B", "3"),
List.of("B", "1"));
Map<String, ArrayList<String>> map = new HashMap<>();
input.forEach(l -> map.computeIfAbsent(
l.get(0),
dummy -> new ArrayList<String>()).add(l.get(1)));
System.out.println(map);
// {A=[1, 3, 4, 7], B=[2, 3, 1]}
感谢您的回答。我将答案组合在一起,创建了一行答案,如下所示:
列表<列表>output=input.stream((.collect(Collectors.groupingBy(o->(String(o.get(0(,Collectors.mapping.map(e->Arrays.asList(e.getKey((,e.getValue((((.collect(Collectors.toList(((;