java8 stream初試,map排序,list去重,統計重復元素個數,獲取map的key集合和value集合


//定義一個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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM