wenchunl

导航

 
It depends on the Int number the Comparator returns. 
 
If return <0, when compare each two element of the collection, if a>b, swap their position. 
If return =0, no need position swapping.
If return >0, when compare each two element of the collection, if a<b, swap their position.

See the below demo code to help you understand this.

 

 1 package lambdaExpression;
 2 
 3 import java.util.Arrays;
 4 import java.util.Collections;
 5 import java.util.List;
 6 
 7 public class Main {
 8 
 9     public static void main(String[] args) {
10         // TODO Auto-generated method stub
11 
12         List<String> names = Arrays.asList("peter", "anna", "mike", "xenia", "mike");
13 
14         System.out.println("names before sort are:");
15         for (String x : names) {
16             System.out.println(x);
17         }
18 
19         // Method 1 , Ascending
20         Collections.sort(names, (String a, String b) -> {
21             return a.compareTo(b);
22         });
23 
24         System.out.println("names After sort1 are: ");
25         myout((String[]) names.toArray());
26 
27         // Method 2 , Descending
28         Collections.sort(names, (String a, String b) -> b.compareTo(a));
29 
30         System.out.println("names After sort2 are: ");
31         myout((String[]) names.toArray());
32 
33         // Method 3 , Ascending
34         Collections.sort(names, (a, b) -> a.compareTo(b));
35 
36         System.out.println("names After sort3 are: ");
37         myout((String[]) names.toArray());
38 
39         // Method 4 , No swapping,keep prior change result
40         Collections.sort(names, (String a, String b) -> {
41             return a.compareTo(a);
42         });
43 
44         System.out.println("names After sort4 are: ");
45         myout((String[]) names.toArray());
46 
47     }
48 
49     public static void myout(String[] names) {
50         for (String x : names) {
51             System.out.println(x);
52         }
53     }
54 
55 }

 

posted on 2017-09-18 17:58  良哥  阅读(180)  评论(0编辑  收藏  举报