这种方式利用了Stream API的sorted方法和Collectors.toMap收集器,同样可以得到按key排序的Map。
Map<String, Integer> map = ImmutableMap.of("0", 3, "1", 8, "0.29", 7, "1.67", 3); System.out.println("原始的map:" +map); System.out.println("根据map的key降序:" + sortByKey(map,true)); System.out.println("根据map的key升序:" + sortByKey(map,false)); System.out.println(...
1、根据key排序 Map<String,String> result = new HashMap<>(); Map<String,String> map = new HashMap<>(); map.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .forEachOrdered(x->result.put(x.getKey(),x.getValue())); 1. 2. 3. 4. 5. 6. 7. 2、根据value排序 Map<Stri...
List<Map<String, Object>> bookList = jdbcTp.queryForList(sql); // 使用java 8的 stream 功能进行排序 // order by author,price desc,publisher /** * 升序返回-1,倒序返回1即可 有多个key需要比较的时候(不考虑null或者""的情况),当第n个key返回的是0的时候继续比较,如果不是 * 则根据第n个key的...
首先使用entrySet().stream() 将Map类型转换为Stream流类型。 然后使用sorted方法排序,排序的依据是Map.Entry.comparingByKey(),也就是按照Map的键排序 最后用collect方法将Stream流转成LinkedHashMap。 其他参数都好说,重点看第三个参数,就是一个merge规则的lambda表达式,与merge方法的第三个参数的用法一致。由于本...
按照map的Key进行排序 publicstaticvoidmain(String[]args){Map<String,Integer>unsortMap=newHashMap<>();unsortMap.put("z",10);unsortMap.put("b",5);unsortMap.put("a",6);unsortMap.put("c",20);unsortMap.put("d",1);unsortMap.put("e",7);unsortMap.put("y",8);unsortMap.put...
2019-04-08 23:12 −熟悉下java8的新特性对map排序操作,干货满满~... superdrew 1 12504 在map中根据value获取key 2019-12-09 10:56 −//根据map的value获取map的key private static String getKey(Map<String,String> map,String value){ String key=""; for (Map.Entry<String, S... ...
可以通过 stream 来使用 comparingByKey 进行排序。 代码语言:java 复制 List<Map.Entry<String,Integer>>collect=map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList()); comparingByValue 也一样,这两个都是使用内部比较器Comparable。