java8 stream初試,map排序,list去重,統計重複元素個數,獲取map的key集合和value集合
阿新 • • 發佈:2019-01-02
//定義一個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);
stream增強了集合的很多操作,真的很是方便啊,j8以前去重、排序、遍歷map獲得value真的很麻煩有木有