当前位置: 代码迷 >> 综合 >> JAVA8 STREAM初试,MAP排序,LIST去重,统计重复元素个数,获取MAP的KEY集合和VALUE集合
  详细解决方案

JAVA8 STREAM初试,MAP排序,LIST去重,统计重复元素个数,获取MAP的KEY集合和VALUE集合

热度:17   发布时间:2023-12-17 09:33:33.0
定义一个100元素的集合,包含A-ZList<String> list = new LinkedList<>();
for (int i =0;i<100;i++){list.add(String.valueOf((char)('A'+Math.random()*('Z'-'A'+1))));}
System.out.println(list);统计集合重复元素出现次数,并且去重返回hashmapMap<String, Long> map = list.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println(map);由于hashmap无序,所以在排序放入LinkedHashMap里(key升序)Map<String, Long> sortMap = new LinkedHashMap<>();
map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> sortMap.put(e.getKey(), e.getValue()));
System.out.println(sortMap);map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(oldValue, newValue) -> oldValue, LinkedHashMap::new));
获取排序后map的key集合List<String> keys = new LinkedList<>();
sortMap.entrySet().stream().forEachOrdered(e -> keys.add(e.getKey()));
System.out.println(keys);获取排序后map的value集合List<Long> values = new LinkedList<>();
sortMap.entrySet().stream().forEachOrdered(e -> values.add(e.getValue()));
System.out.println(values);
  相关解决方案