使用Java,没有第三方库的帮助,有旧的方式和新的方式。过去,使用 Collections.sort(..) 进行排序很容易。
旧方法的挑战是需要大量的代码来对值进行分组。
- Input: List<String>
- Output: Map<Character,<List<String>>
- The key of map is 'A' to 'Z'
- Each list in the map are sorted.
旧爪哇
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);
新 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);
新的Java 8,源数据已经作为“流”
正如@KevinO所建议的
Map<Character, List<String>> result = Stream
.of( "Apple", "Ananas", "Mango", "Banana","Beer")
.sorted()
.collect(Collectors.groupingBy(it -> it.charAt(0)))
System.out.println(result);