怎么在java8中使用stream 操作map

这篇文章给大家介绍怎么在java8中使用stream 操作map,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1、map 根据value排序

Map<String,BigDecimal> map =new HashMap<>();
map.put("one", 0.08);
map.put("two", 0.1);
map.put("three", 0.2);
map.put("four", 0.91);

上面是项目中的一个中间结果,我们需要对这个map根据value值倒序排序,下面给出工具类:

  public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    Map<K, V> result = new LinkedHashMap<>();
 
    map.entrySet().stream()
        .sorted(Map.Entry.<K, V>comparingByValue()
            .reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
    return result;
  }

当然如果我们想根据map的key进行排序,需要对上面的工具类进行小小的修改,代码如下:

 public <K extends Comparable<? super K>, V > Map<K, V> sortByKey(Map<K, V> map) {
    Map<K, V> result = new LinkedHashMap<>();
 
    map.entrySet().stream()
        .sorted(Map.Entry.<K, V>comparingByKey()
            .reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
    return result;
  }

我们可以看到,如果我们需要根据key排序,就需要让key 继承 Comparable ,也就说我们需要对待排序的字段继承 Comparable接口。另一个问题就是,上面的这种写法排序效果是 降序排序,如果我们需要升序排序的话,只需要将上面的.reversed()关键字限制去掉即可。

 public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    Map<K, V> result = new LinkedHashMap<>();
 
    map.entrySet().stream()
        .sorted(Map.Entry.<K, V>comparingByValue()
            ).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
    return result;
  }

关于怎么在java8中使用stream 操作map就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。