使用lambdas和stream按值排序映射

时间:2015-04-10 17:41:43

标签: java java-8 java-stream

我是Java 8的新手,不知道如何使用流和它的排序方法。如果我有如下地图,如何按值对该地图进行排序,以便只使用Java 8获取前10个条目。

HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("a", 10);
        map.put("b", 30);
        map.put("c", 50);
        map.put("d", 40);
        map.put("e", 100);
        map.put("f", 60);
        map.put("g", 110);
        map.put("h", 50);
        map.put("i", 90);
        map.put("k", 70);
        map.put("L", 80);

我知道在Java 8之前,我们可以将此链接排序:https://stackoverflow.com/a/109389/4315608

4 个答案:

答案 0 :(得分:72)

您随时可以开始阅读documentationsome tutorials

map.entrySet().stream()
        .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) 
        .limit(10) 
        .forEach(System.out::println); // or any other terminal method

参考

http://www.leveluplunch.com/java/examples/sort-order-map-by-values/

答案 1 :(得分:8)

请参阅堆栈流程线程here和示例here

Map<String,Person> map = new HashMap<>();
map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));

Map<String,Person> sortedNewMap = map.entrySet().stream().sorted((e1,e2)->
        e1.getValue().getLocation().compareTo(e2.getValue().getLocation()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (e1, e2) -> e1, LinkedHashMap::new));
sortedNewMap.forEach((key,val)->{
    System.out.println(key+ " = "+ val.toString());
});

答案 2 :(得分:2)

List<Map.Entry<String, Integer>> entries = newArrayList(map.entrySet());
Collections.sort(entries, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));
List<Map.Entry<String, Integer>> top10 = entries.subList(0, Math.min(entries.size(), 10));

答案 3 :(得分:1)

如果要按值对象的整数或浮点值排序

Map<String,Person> map = new HashMap<>();
map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));

你可以使用,

Map<String,Person> sortedNewMap = map.entrySet().stream().sorted((e1,e2)->
        Integer.compare(e1.getValue().getAge(), e2.getValue().getAge()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (e1, e2) -> e1, LinkedHashMap::new));