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 ~