java简洁地根据map中的value或key进行排序

先上代码再解释

public static void main(String[] args) {
	        Map<String,Integer> map = new HashMap<>();
	        map.put("nine",9);
	        map.put("six",6);
	        map.put("name",6);
	        map.put("eight",8);
	        map.put("zero",0);
	        map.put("one",1);
	        map.put("four",4);
	        map.put("two",2);
	        sortMap(map);
	    }
	    public static void sortMap(Map<String, Integer> map){
	    	map.entrySet().stream().sorted(Comparator.comparing(e->e.getValue())).forEachOrdered(e->System.out.println(e));
	    }
其中我们可以看到根据map中的value排序只用了一行代码
map.entrySet().stream().sorted(Comparator.comparing(e->e.getValue())).forEachOrdered(e->System.out.println(e));

接着来解释一下,在eclipse将鼠标放到sorted上会出现下面提示信息,

Stream<Entry<StringInteger>> java.util.stream.Stream.sorted(Comparator<? super Entry<StringInteger>> comparator)

即表示sorted的参数为一个关于Entry<StringInteger>的比较器,然后我们想通过调用Comparator的方法comparing构造出一个比较器,使用类似的方法可知,comparing的功能为提取排序关键词,然后通过lamda表达式简洁地构造了一个函数,e->e.getValue()和e::e.getValue()是相同的,然后对一次对每个排好序的entry进行输出操作。

类似函数

1、进行降序排序

map.entrySet().stream().sorted(Comparator.comparing(e->-e.getValue())).forEachOrdered(e->System.out.println(e));

2、将结果保存在List中

List<Map.Entry<String,Integer>> sorted = new LinkedList<>();
map.entrySet().stream().sorted(Comparator.comparing(e->e.getValue())).forEachOrdered(e->sorted.add(e));

猜你喜欢

转载自blog.csdn.net/djd566/article/details/79468004