• How can I determine ascending or descending of the method Collections.sort


    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 }
  • 相关阅读:
    个人工作总结07
    uboot是用来干什么的,有什么作用?
    交叉编译器的命名规则及详细解释(arm/gnu/none/linux/eabi/eabihf/gcc/g++)
    C++中explicit关键字的使用
    ubuntu 虚拟机下使用摄像头
    用CMAKE编译OpenCV 3.4.2+Opencv Contrib 3.4生成可执行包
    人脸识别:objectDetection
    opencv 3 -- waitKey()函数
    CreateThread与_beginthreadex本质区别
    lib文件和dll文件
  • 原文地址:https://www.cnblogs.com/wenchunl/p/7544378.html
Copyright © 2020-2023  润新知