[英]Creating a Map<String, ArrayList<String[]>> from ArrayList<String[]> in Java
I have an ArrayList of String Array and the 2nd element of every String Array contains a name.我有一个 ArrayList 的字符串数组,每个字符串数组的第二个元素都包含一个名称。 I want to create a Map where it's Key is the name and Value is an ArrayList of all String Array which has the name.我想创建一个 Map,其中 Key 是名称,Value 是所有具有名称的字符串数组的 ArrayList。
How can I achive this in Java?我怎样才能在 Java 中实现这个目标?
Input: ArrayList<String[]>输入:ArrayList<String[]>
{"1", "NameABC", "somestring"}
{"2", "NameDEF", "somestring"}
{"3", "NameDEF", "somestring"}
{"4", "NameABC", "somestring"}
{"5", "NameXYZ", "somestring"}
Output: Map<String, ArrayList<String[]> Output:地图<字符串,数组列表<字符串[]>
Key = NameABC, Value = ArrayList of String[] where every String[] has NameABC Key = NameABC,Value = String[] 的 ArrayList,其中每个 String[] 都有 NameABC
Key = NameXYZ, Value = ArrayList of String[] where every String[] has NameXYZ Key = NameXYZ,Value = String[] 的 ArrayList,其中每个 String[] 都有 NameXYZ
I've tried using stream.collect(Collectors.toMap())
but I can't figure out how to achieve the proper output.我试过使用stream.collect(Collectors.toMap())
但我不知道如何实现正确的 output。
Streams and collectors are not always the best option:流和收集器并不总是最好的选择:
Map<String, List<String[]>> map = new HashMap<>();
myListOfArrays.forEach(arr -> map.computeIfAbsent(arr[1], x -> new ArrayList<>()).add(arr));
If the key can be null and you want to store it under a blank, use the expression arr[1] == null? "": arr[1]
如果密钥可以是 null 并且您想将其存储在空白下,请使用表达式arr[1] == null? "": arr[1]
arr[1] == null? "": arr[1]
instead: arr[1] == null? "": arr[1]
改为:
myListOfArrays.forEach(arr -> map.computeIfAbsent(arr[1] == null ? "" : arr[1], x -> new ArrayList<>()).add(arr));
Try this -尝试这个 -
List<String[]> l1 = new ArrayList<>();
l1.add(new String[]{"1", "NameABC", "somestring"});
l1.add(new String[]{"2", "NameDEF", "somestring"});
l1.add(new String[]{"3", "NameDEF", "somestring"});
l1.add(new String[]{"4", "NameABC", "somestring"});
l1.add(new String[]{"5", "NameXYZ", "somestring"});
Map<String, List<String[]>> map = l1.stream().collect(Collectors.groupingBy(arr -> arr[1]));
for (Map.Entry<String, List<String[]>> entry : map.entrySet()) {
String key = entry.getKey();
List<String[]> val = entry.getValue();
System.out.println(key + " -- "+ val);
}
You can use Stream
with groupingBy()
:您可以将Stream
与groupingBy()
一起使用:
public static Map<String, List<String[]>> convert(List<String[]> data) {
return data.stream().collect(Collectors.groupingBy(arr -> arr[1]));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.