Skip to content

Instantly share code, notes, and snippets.

@karlmutch
Created June 3, 2015 18:29
Show Gist options
  • Save karlmutch/6cf4e1b864e750ff97be to your computer and use it in GitHub Desktop.
Save karlmutch/6cf4e1b864e750ff97be to your computer and use it in GitHub Desktop.
Using Java, with no help from 3rd party libraries, there is the old way and the new way. Just sorting used to be easy with Collections.sort(..).
The challenge with the old way was that a lot of code was required to group the values.
- Input: List<String>
- Output: Map<Character,<List<String>>
- The key of map is 'A' to 'Z'
- Each list in the map are sorted.
Old Java
List<String> keywords = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer");
Map<Character, List<String>> result = new HashMap<Character, List<String>>();
for(String k : keywords) {
char firstChar = k.charAt(0);
if(!result.containsKey(firstChar)) {
result.put(firstChar, new ArrayList<String>());
}
result.get(firstChar).add(k);
}
for(List<String> list : result.values()) {
Collections.sort(list);
}
System.out.println(result);
New Java 8
List<String> keywords = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer");
Map<Character, List<String>> result = keywords.stream().sorted()
.collect(Collectors.groupingBy(it -> it.charAt(0)));
System.out.println(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment