Converting a text file to Map<String, List<String>> using lambda
Map and collect:
Map<String, List<String>> res = lines.stream()
.map(s -> Arrays.asList(s.split("=")))
.collect(HashMap::new,
(map, item) -> map.computeIfAbsent(item.get(0), k -> new ArrayList<>()).add(item.get(1)),
HashMap::putAll);
Or map and group by:
Map<String, List<String>> res = lines.stream()
.map(s -> Arrays.asList(s.split("=")))
.collect(Collectors.groupingBy(s -> s.get(0), Collectors.mapping(v->v.get(1), Collectors.toList())));
Stream.collect
documentation
Use Collectors.mapping
while groupingBy
, for more information look at this doc-with-example
Map<String, List<String>> conf = stream.
collect(Collectors.groupingBy(s -> s.split("=")[0], Collectors.mapping(v->v.split("=")[1], Collectors.toList())));
System.out.println(conf); //{A=[groupA1, groupA2, groupA3], B=[groupB1, groupB2]}
If you are open to using a third-party library, the following will work using Eclipse Collections.
ListMultimap<String, String> strings = stream
.map(s -> s.split("="))
.collect(Collectors2.toListMultimap(a -> a[0], a -> a[1]));
Collectors2.toListMultimap
takes a Function
to calculate the key and a separate Function
to calculate the value. The ListMultimap<K, V>
type is equivalent to Map<K, List<V>>
.
Note: I am a committer for Eclipse Collections.