Converting a text file to Map<String, List<String>> using lambda

  • A+

I am trying to convert the following text input file:

A=groupA1 A=groupA2 A=groupA3 B=groupB1 B=groupB2 

into Map<String, List<String>> by splitting each line on "="

So far I manged to get this sort of output:

KEY: A VALUE: A=groupA1 VALUE: A=groupA2 VALUE: A=groupA3 KEY: B VALUE: B=groupB1 VALUE: B=groupB2 

using such code:

File reqFile = new File("test.config");  try (Stream<String> stream = Files.lines(reqFile.toPath())) {     Map<String, List<String>> conf = stream.collect(Collectors.groupingBy(s -> s.split("=")[0]));     for (Map.Entry<String, List<String>> entry: conf.entrySet()) {         System.out.println("KEY: " + entry.getKey());         for (String value : entry.getValue()) {             System.out.println("VALUE: " + value);         }     } } catch (Exception e) {     e.printStackTrace(); } 

How to tweak the above lambda to get something like this:

KEY: A VALUE: groupA1 VALUE: groupA2 VALUE: groupA3 KEY: B VALUE: groupB1 VALUE: groupB2 


Map and collect:

Map<String, List<String>> res =     .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 =         .map(s -> Arrays.asList(s.split("=")))         .collect(Collectors.groupingBy(s -> s.get(0), Collectors.mapping(v->v.get(1), Collectors.toList()))); 
  1. Stream.collect documentation


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: