简体   繁体   中英

List of Strings to hashmap using Streams

I have a "," separated String array like this

a b c d,
f b h j,
l p o i,

I would like this to be converted to a Hashmap like HashMap<String, List<String>> such that second element in list (delimited by space becomes key and the 3rd element becomes value) So, This should become

b -> c,h
p -> o

I want to use Streams API and I think this is the way to go:

List<String> entries = new ArrayList<>();
HashMap<String, List<String>> map = new HashMap<>();

HashMap<String, List<String>> newMap = entries.stream()
    .collect(line -> {
        if (map.contains(line.split(" ")[1])) {
            // Get existing list and add the element
            map.get(line.split(" ")[1].add(line.split(" ")[1]));
        } else {
            // Create a new list and add
            List<String> values = new ArrayList<>();
            values.add(line.split(" ")[1]);
            map.put(line.split(" ")[0], values);
        }
    });

Is there any better way? How exactly should I return Hashmap from collect function?

You can use the Collectors.groupingBy as shown below to group the inputs (follow the inline comments):

String[] inputs = {"a b c d,", "f b h j,", "l p o i,"};
Map<String, List<String>> results =  
     Arrays.stream(inputs).map(s -> s.split(" ")).//splt with space
     collect(Collectors.groupingBy(arr -> arr[1], // Make second element as the key
         Collectors.mapping(arr -> arr[2], // Make third element as the value
                            Collectors.toList())));//collect the values to List
 System.out.println(results);

Output:

{p=[o], b=[c, h]}

I suggest you read the API here to understand how Collectors.groupingBy along with Collectors.mapping works.

You can achieve the task at hand using a groupingBy collector along with Collectors.mapping as a downstream collector.

Map<String, List<String>> collect =
            myList.stream()
                  .map(s -> s.split(" "))
                  .collect(Collectors.groupingBy(a -> a[1],  
                         Collectors.mapping(a -> a[2], Collectors.toList())));

output:

{p=[o], b=[c, h]}

if you want to maintain insertion order then you can specify a LinkedHashMap like this:

Map<String, List<String>> collect =
                myList.stream()
                      .map(s -> s.split(" "))
                      .collect(Collectors.groupingBy(s -> s[1],
                             LinkedHashMap::new,
                              Collectors.mapping(s -> s[2], Collectors.toList())));

output:

{b=[c, h], p=[o]}

If you want HashMap , not just any Map

HashMap<String, List<String>> output =myList.stream().map(s -> s.split(" "))
            .collect(Collectors.groupingBy((s) -> s[1],
                    HashMap::new,
                    Collectors.mapping(
                            (s) -> s[2],
                            Collectors.toList())));

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