Skip to content

Instantly share code, notes, and snippets.

@shihpeng
Created June 4, 2017 06:09
Show Gist options
  • Save shihpeng/d4b996643c1ef7b3678e7c496265ac2f to your computer and use it in GitHub Desktop.
Save shihpeng/d4b996643c1ef7b3678e7c496265ac2f to your computer and use it in GitHub Desktop.
Convert a string to map with duplication
/*
* How to convert a string: "name1:prop1,name1:prop2,name2:prop3" to a map of the following form:
* {name1=[prop1, prop2], name2=[prop3]}
*/
// Before Java 8
String[] tokens = line.split(",");
Map<String, List<String>> map = new HashMap<>();
for(String token : tokens) {
String[] pair = token.split(":");
List<String> list = map.get(pair[1]);
if(list == null) {
list = new ArrayList<>();
}
list.add(pair[0]);
map.put(pair[1], list);
}
// Using Java 8 Stream API
Map<String, List<String>> result = Arrays.stream(line.split(","))
.map(s -> s.split(":"))
.collect(groupingBy(pair -> pair[1], mapping(pair -> pair[0], toList())));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment