使用Stream对HashMap进行排序
2020-07-20 本文已影响0人
AbstractCulture
话不多说。直接贴代码
HashMap<String, BigDecimal> map = new HashMap<>();
map.put("a", BigDecimal.valueOf(1231));
map.put("d", BigDecimal.valueOf(55));
map.put("c", BigDecimal.valueOf(223));
LinkedHashMap<String, BigDecimal> collect = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
collect.entrySet().stream().forEach(c-> System.out.println(c.getKey()+" "+c.getValue()));
Result

按照特定序列进行排序
List<String> rules = Arrays.asList("a", "d", "c");
HashMap<String, BigDecimal> map = new HashMap<>();
map.put("a", BigDecimal.valueOf(1));
map.put("d", BigDecimal.valueOf(2));
map.put("c", BigDecimal.valueOf(3));
LinkedHashMap<String, BigDecimal> collect = map.entrySet().stream().sorted(Comparator.comparingInt(k -> rules.indexOf(k.getKey())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
collect.entrySet().stream().forEach(c-> System.out.println(c.getKey()+" "+c.getValue()));
Result

Collectors.toMap()有三个签名:
1.Collects.toMap(Map.Entry::getKey, Map.Entry::getValue)
;
参数一是你转化后的key,参数二是你转化后的value,此方法下,发生碰撞会直接丢异常
2.Collects.toMap(Map.Entry::getKey, Map.Entry::getValue,(oldValue, newValue) -> oldValue)
;
参数一二同上,参数三是发生碰撞时进行什么处理。这里是保持旧值
3.Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)
参数一二三同上,最后一个是你想生成的Map结构,这里采用的是LinkedHashMap.如果想实现排序后仍然保持Map结构,那么LinkedHashMap是不错的选择。
Collects.toMap的妙用
给定一个key列表,获取hashMap中的子Map
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("a","a");
hashMap.put("b","b");
hashMap.put("c","c");
hashMap.put("d","d");
hashMap.put("e","e");
hashMap.put("f","f");
List<String> re = Arrays.asList("a", "b", "c");
Map<String, Object> resultMap = re.stream().collect(Collectors.toMap(key -> key, hashMap::get));
resultMap.forEach((k,v)-> System.out.println(k+","+v));
输出:
