简体   繁体   中英

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. 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.

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] arr[1] == null? "": arr[1] instead:

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() :

public static Map<String, List<String[]>> convert(List<String[]> data) {
    return data.stream().collect(Collectors.groupingBy(arr -> arr[1]));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM