zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    ie6下absolute:fixed问题,完美兼容
    ajax传输 基础一
    获取ip的ip138.com
    css 常用代码解析
    QQ客服出现“企业QQ在线咨询无权限在当前场景使用!” 问题
    用js实现QQ自定义在线图片
    getElement的几中属性介绍
    Ecshop 单选按钮组功能 颜色多选
    IE6完美解决fix问题
    PHP站内搜索、多关键字、加亮显示
  • 原文地址:https://www.cnblogs.com/wenchunl/p/7544378.html
Copyright © 2011-2022 走看看