@@ -50,14 +50,49 @@ public void testSortMapWithValue(){
5050 ArrayList <String > keyList = new ArrayList <>(map .keySet ());
5151 System .out .println (">>> (before sort) keyList = " + keyList );
5252
53- Collections .sort (keyList , (x ,y ) -> {
54- // compare val, bigger first (decreasing order)
55- int valDiff = map .get (y ) - map .get (x );
56- if (valDiff == 0 ){
57- // compare key len, shorter first (increasing order)
58- return x .length () - y .length ();
53+
54+
55+ /**
56+ * NOTE !!!
57+ *
58+ * Why we can use `lambda expression` for above Comparator's compare method ?
59+ *
60+ * -> The reason we can use a lambda expression
61+ * in this case is that the Comparator interface in Java is a functional interface,
62+ * which means it has exactly one abstract method. The method signature is:
63+ *
64+ *
65+ * To summarize:
66+ *
67+ * - The Comparator interface has a single abstract method (compare(T o1, T o2)).
68+ * - This allows Java to use lambda expressions to provide an implementation for that method.
69+ * - The lambda expression is shorthand for an anonymous inner class that implements the compare method directly.
70+ *
71+ */
72+
73+
74+ /** V1 : lambda expression */
75+ // Collections.sort(keyList, (x,y) -> {
76+ // // compare val, bigger first (decreasing order)
77+ // int valDiff = map.get(y) - map.get(x);
78+ // if (valDiff == 0){
79+ // // compare key len, shorter first (increasing order)
80+ // return x.length() - y.length();
81+ // }
82+ // return valDiff;
83+ // });
84+
85+ /** V2 : regular way (use Comparator, then override `compare` method) */
86+ Collections .sort (keyList , new Comparator <String >() {
87+ @ Override
88+ public int compare (String x , String y ) {
89+ int valDiff = map .get (y ) - map .get (x );
90+ if (valDiff == 0 ){
91+ // compare key len, shorter first (increasing order)
92+ return x .length () - y .length ();
93+ }
94+ return valDiff ;
5995 }
60- return valDiff ;
6196 });
6297
6398 System .out .println (">>> (after sort) keyList = " + keyList );
0 commit comments