Reputation: 11
I have an ArrayList of String Array and the 2nd element of every String Array contains a name. 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.
How can I achive this in Java?
Input: ArrayList<String[]>
{"1", "NameABC", "somestring"}
{"2", "NameDEF", "somestring"}
{"3", "NameDEF", "somestring"}
{"4", "NameABC", "somestring"}
{"5", "NameXYZ", "somestring"}
Output: Map<String, ArrayList<String[]>
Key = NameABC, Value = ArrayList of String[] where every String[] has NameABC
Key = NameXYZ, Value = ArrayList of String[] where every String[] has NameXYZ
I've tried using stream.collect(Collectors.toMap())
but I can't figure out how to achieve the proper output.
Upvotes: 0
Views: 108
Reputation: 154
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);
}
Upvotes: 1
Reputation: 18255
You can use Stream
with groupingBy()
:
public static Map<String, List<String[]>> convert(List<String[]> data) {
return data.stream().collect(Collectors.groupingBy(arr -> arr[1]));
}
Upvotes: 0
Reputation: 425378
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]
instead:
myListOfArrays.forEach(arr -> map.computeIfAbsent(arr[1] == null ? "" : arr[1], x -> new ArrayList<>()).add(arr));
Upvotes: 1