David Hoeck
David Hoeck

Reputation: 1

How to group stringarray to map?

i'd tried for the last few hours two fix this small problem. I want to read from a txt file using:

Stream<String> stream = Files.lines(Paths.get(fileName))

the Input looks like:

b -> l;
c -> a;
a -> d;    
c -> l; 

Now i want to map it like this.

{a,=d, b=l, c=[a,l]}

I tried to do this with the java stream API:

stream.map(x->x.split(" -> ")).collect(Collectors.toMap(x->x[0], 

x->x[1]));

the Problem is toMap throws an exception if i got duplicate keys.

Is there a way to allow duplicate keys and store the values in a list?.

Upvotes: 0

Views: 110

Answers (1)

bart.s
bart.s

Reputation: 688

All you need to do is to use groupingBy with a proper mapping.

Map<String, Set<String>> result = list.stream().map(it -> it.split(" -> ")).
  collect(Collectors.groupingBy(t -> t[0], 
   Collectors.mapping(strings -> strings[1], Collectors.toSet())));

Upvotes: 1

Related Questions