Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

java - Sort map by value using lambdas and streams

I'm new to Java 8, not sure how to use streams and it's methods to sort. If I have map as below, how to sort this map by value to take only top 10 entries using Java 8.

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);

I know before Java 8, we can sort as this link: https://stackoverflow.com/a/109389/4315608

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can always start reading the documentation and some tutorials.

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

Reference

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...