话不多说。直接贴代码
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
Collects.toMap的妙用
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));
输出: