java8 stream 操作map根据key或者value排序的实现
引言
最近小编自己一个人在负责一个项目的后台开发,其中有一部分是统计相关的功能,所以需要一些排序或者分组的操作,之前这种操作小编觉得还是比较麻烦的,虽热有一些现成的工具类,但是工具类的写法也是比较复杂的,但是如果使用java8stream流的话就比较简单了,并且代码量会大大的减少,下面总结几个对map的操作。
1、map根据value排序
Mapmap=newHashMap<>(); map.put("one",0.08); map.put("two",0.1); map.put("three",0.2); map.put("four",0.91);
上面是项目中的一个中间结果,我们需要对这个map根据value值倒序排序,下面给出工具类:
public>Map sortByValue(Map map){ Map result=newLinkedHashMap<>(); map.entrySet().stream() .sorted(Map.Entry. comparingByValue() .reversed()).forEachOrdered(e->result.put(e.getKey(),e.getValue())); returnresult; }
当然如果我们想根据map的key进行排序,需要对上面的工具类进行小小的修改,代码如下:
public,V>Map sortByKey(Map map){ Map result=newLinkedHashMap<>(); map.entrySet().stream() .sorted(Map.Entry. comparingByKey() .reversed()).forEachOrdered(e->result.put(e.getKey(),e.getValue())); returnresult; }
我们可以看到,如果我们需要根据key排序,就需要让key继承Comparable,也就说我们需要对待排序的字段继承Comparable接口。另一个问题就是,上面的这种写法排序效果是降序排序,如果我们需要升序排序的话,只需要将上面的.reversed()关键字限制去掉即可。
public>Map sortByValue(Map map){ Map result=newLinkedHashMap<>(); map.entrySet().stream() .sorted(Map.Entry. comparingByValue() ).forEachOrdered(e->result.put(e.getKey(),e.getValue())); returnresult; }
小结
java8提供了一些非常简便的写法,我们还是需要多用一些,希望能对读者有些帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。