话不多说,直接上代码
- List Count
public static void main(String[] args) {
List<String> list = Arrays.asList("beijing", "shanghai", "guangzhou", "shenzhen", "beijing");
Map<String, Long> collect = list.stream()
.collect(Collectors.groupingBy(o -> o, Collectors.counting()));
System.out.println(collect);
// out => {guangzhou=1, shanghai=1, shenzhen=1, beijing=2}
}
- List Word Count
public static void main(String[] args) {
List<String> list = Arrays.asList("beijing shanghai guangzhou"
, "beijing guangzhou"
, "beijing", "beijing");
Map<String, Long> collect = list.stream()
.flatMap(o -> Stream.of(o.split(" ")))
.collect(Collectors.groupingBy(o -> o, Collectors.counting()));
System.out.println(collect);
// out => {guangzhou=2, shanghai=1, beijing=4}
}
如果要包含元素
- 使用JDK自带集合类
public static void main(String[] args) {
List<String> list = Arrays.asList("beijing", "shanghai", "guangzhou", "shenzhen", "beijing");
Map<String, List<String>> collect
= list.stream().collect(Collectors.groupingBy(o -> o));
System.out.println(collect);
// out => {guangzhou=[guangzhou], shanghai=[shanghai], shenzhen=[shenzhen], beijing=[beijing, beijing]}
}
- 使用Spring 的 LinkedMultiValueMap
public static void main(String[] args) {
List<String> list = Arrays.asList("beijing", "shanghai", "guangzhou", "shenzhen", "beijing");
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap();
list.stream().forEach(o -> map.add(o, o));
System.out.println(map);
// out => {beijing=[beijing, beijing], shanghai=[shanghai], guangzhou=[guangzhou], shenzhen=[shenzhen]}
}