Operate HashMap and lambdahashmap using lambda expressions

Source: Internet
Author: User

Operate HashMap and lambdahashmap using lambda expressions

Before Java 8, if you want to sort values by map values, it is complicated to see how to sort HashMap by value

Now it is much easier to use lambda expressions.

Map <String, Integer> map = new HashMap <> (); map. put ("derek", 24); map. put ("dad", 51); map. put ("mom", 46); List <Map. entry <String, Integer> list = new ArrayList <> (); list. addAll (map. entrySet (); // Collections. sort (list, new Comparator <Map. entry <String, Integer> () {// public int compare (Map. entry <String, Integer> m1, Map. entry <String, Integer> m2) {// return m1.getValue ()-m2.getValue (); //}); Collections. sort (list, (m1, m2)-> m1.getValue ()-m2.getValue (); list. forEach (m-> System. out. println (m. getKey ()));

The commented out part is the previous method. Now you only need a brief line of code to do this, and the traversal is much more convenient.

Lambda expressions make Java's functional programming really sharp. With the enhanced type inference in Java 8, the Code becomes concise and easy to understand ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.