java8 stream初试,map排序,list去重,统计重复元素个数,获取map的key集合和value集合

Wesley131563 阅读
文章目录
//定义一个100元素的集合,包含A-Z
List<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);
//统计集合重复元素出现次数,并且去重返回hashmap
Map<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的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);
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册⭐️ Admin快速开发: https://show.cool-admin.com/
赞 0⭐️ 官方文档: https://cool-js.com
赞 0⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld
赞 0