Detailed explanation of Collections.sort() sorting in Java

Please indicate the source for reprinting: http://blog.csdn.net/xx326664162/article/details/52227690 Article from: Xue Xuan's blog

You can also check my other similar articles, which will also give you a certain amount of receipt

The first: Comparable sorting interface

If a class implements the Comparable interface, it means "this class supports sorting". Assuming "there is a List (or array), the elements in it are classes that implement the Comparable interface", then the List (or array) can be sorted by Collections.sort (or Arrays.sort).

In addition, an "object of a class implementing the Comparable interface" can be used as a key in an "ordered map (such as a TreeMap)" or as an element in an "ordered set (TreeSet)" without specifying a comparator.

class A implements Comparable<A>{  
    private String name;  
    private Integer order;  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  

    public Integer getOrder() {  
        return order;  
    }  
    public void setOrder(Integer order) {  
        this.order = order;  
    }  
    @Override  
    public String toString() {  
        return "name is "+name+" order is "+order;  
    }  
    @Override  
    public int compareTo(A a) {  
        return this.order.compareTo(a.getOrder());  
    }  

} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
List< A> list = new ArrayList< A>(); 
  • 1
  • Class A implements the interface Comparable and implements the compareTo() method
  • Sort by calling Collections.sort(lists) 

The second: Comparator comparator interface.

If we need to control the order of a class, and the class itself does not support sorting (that is, it does not implement the Comparable interface); we can create a "comparator" to sort. This "comparator" only needs to implement the Comparator interface.

  • Collections.sort(list, new PriceComparator())

    • Parameter 1: The list to be sorted
    • Parameter 2: Comparator, a class that implements the Comparator interface, returns an int value, which is equivalent to a flag, telling the sort method in which order to sort the list.
  • Comparator is an interface that can override the compare() and equals() methods for comparison functions; if it is null, the default order of elements is used, such as a,b,c,d,e,f,g , that is, a, b, c, d, e, f, g, and of course numbers.

    • compare(a,b) method: Returns a negative integer, zero, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second argument, respectively.
    • equals(obj) method: Returns true only if the specified object is also a Comparator and enforces the same ordering as this Comparator.

Two methods example

package com.jabberchina.test;  

import java.util.ArrayList;  
import java.util.Collections;  
import java.util.Comparator;  
import java.util.List;  

public class SortTest {  


    static class A implements Comparable<A> {
        private String name;
        private Integer order;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getOrder() {
            return order;
        }

        public void setOrder(Integer order) {
            this.order = order;
        }

        @Override
        public String toString() {
            return "name is " + name + " order is " + order;
        }

        @Override
        public int compareTo(A a) {
            return this.order.compareTo(a.getOrder());
        }

    }

    static class B {
        private String name;
        private String order;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getOrder() {
            return order;
        }

        public void setOrder(String order) {
            this.order = order;
        }

        @Override
        public String toString() {
            return "name is " + name + " order is " + order;
        }
    }

    public static void main(String[] args) {

        //第一种方法示例:
        List<String> lists = new ArrayList<String>();
        lists.add("5");
        lists.add("2");
        lists.add("9");
        //lists中的对象String 本身含有compareTo方法,所以可以直接调用sort方法,按自然顺序排序,即升序排序
        Collections.sort(lists);

        //第一种方法示例:
        List<A> listA = new ArrayList<A>();
        A a1 = new A();
        a1.setName("a1");
        a1.setOrder(1);
        A a2 = new A();
        a2.setName("a2");
        a2.setOrder(2);
        listA.add(a1);
        listA.add(a2);
        //list中的对象A实现Comparable接口
        Collections.sort(listA);

        //第二种方法示例:
        List<B> listB = new ArrayList<B>();
        B b1 = new B();
        b1.setName("b1");
        b1.setOrder("a");
        B b2 = new B();
        b2.setName("b2");
        b2.setOrder("b");
        listB.add(b1);
        listB.add(b2);
        //根据Collections.sort重载方法来实现
        Collections.sort(listB, new Comparator<B>() {
            @Override
            public int compare(B b1, B b2) {
                return b1.getOrder().compareTo(b2.getOrder());
            }
        });

        System.out.println(lists);
        System.out.println(listA);
        System.out.println(listB);
    } 
}  

打印的结果为:  
[2, 5, 9]
[name is a1 order is 1, name is a2 order is 2]
[name is b1 order is a, name is b2 order is b] 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119

Here is another example of method one:

Method 2 is a strategy pattern that can flexibly replace comparators to achieve different sorting

Book entity class:

public class Book implements Comparable { // 定义名为Book的类,默认继承自Object类  
    public int id;// 编号  
    public String name;// 名称  
    public double price; // 价格  
    private String author;// 作者  
    public GregorianCalendar calendar;// 出版日期  

    public Book() {  
        this(0, "X", 0.0, new GregorianCalendar(), "");  
    }  

    public Book(int id, String name, double price, GregorianCalendar calender,  
            String author) {  
        this.id = id;  
        this.name = name;  
        this.price = price;  
        this.calendar = calender;  
        this.author = author;  
    }  

    // 重写继承自父类Object的方法,满足Book类信息描述的要求  
    public String toString() {  
        String showStr = id + "\t" + name; // 定义显示类信息的字符串  
        DecimalFormat formatPrice = new DecimalFormat("0.00");// 格式化价格到小数点后两位  
        showStr += "\t" + formatPrice.format(price);// 格式化价格  
        showStr += "\t" + author;  
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy年MM月dd日");  
        showStr += "\t" + formatDate.format(calendar.getTime()); // 格式化时间  
        return showStr; // 返回类信息字符串  
    }  

    public int compareTo(Object obj) {// Comparable接口中的方法  
        Book b = (Book) obj;  
        return this.id - b.id; // 按书的id比较大小,用于默认排序  
    }  

    public static void main(String[] args) {  
        Book b1 = new Book(10000, "红楼梦", 150.86, new GregorianCalendar(2009,  
                01, 25), "曹雪芹、高鄂");  
        Book b2 = new Book(10001, "三国演义", 99.68, new GregorianCalendar(2008, 7,  
                8), "罗贯中 ");  
        Book b3 = new Book(10002, "水浒传", 100.8, new GregorianCalendar(2009, 6,  
                28), "施耐庵 ");  
        Book b4 = new Book(10003, "西游记", 120.8, new GregorianCalendar(2011, 6,  
                8), "吴承恩");  
        Book b5 = new Book(10004, "天龙八部", 10.4, new GregorianCalendar(2011, 9,  
                23), "搜狐");  
        TreeMap tm = new TreeMap();  
        tm.put(b1, new Integer(255));  
        tm.put(b2, new Integer(122));  
        tm.put(b3, new Integer(688));  
        tm.put(b4, new Integer(453));  
        tm.put(b5, new Integer(40));  
        Iterator it = tm.keySet().iterator();  
        Object key = null, value = null;  
        Book bb = null;  
        while (it.hasNext()) {  
            key = it.next();  
            bb = (Book) key;  
            value = tm.get(key);  
            System.out.println(bb.toString() + "\t库存:" + tm.get(key));  
        }  
    }  
}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

Custom comparator and test class:

package com.tjcyjd.comparator;  

import java.util.ArrayList;  
import java.util.Collections;  
import java.util.Comparator;  
import java.util.GregorianCalendar;  
import java.util.Iterator;  
import java.util.List;  

public class UseComparator {  
    public static void main(String args[]) {  
        List<Book> list = new ArrayList<Book>(); // 数组序列  
        Book b1 = new Book(10000, "红楼梦", 150.86, new GregorianCalendar(2009,  
                01, 25), "曹雪芹、高鄂");  
        Book b2 = new Book(10001, "三国演义", 99.68, new GregorianCalendar(2008, 7,  
                8), "罗贯中 ");  
        Book b3 = new Book(10002, "水浒传", 100.8, new GregorianCalendar(2009, 6,  
                28), "施耐庵 ");  
        Book b4 = new Book(10003, "西游记", 120.8, new GregorianCalendar(2011, 6,  
                8), "吴承恩");  
        Book b5 = new Book(10004, "天龙八部", 10.4, new GregorianCalendar(2011, 9,  
                23), "搜狐");  
        list.add(b1);  
        list.add(b2);  
        list.add(b3);  
        list.add(b4);  
        list.add(b5);  
        // Collections.sort(list); //没有默认比较器,不能排序  
        System.out.println("数组序列中的元素:");  
        myprint(list);  

        Collections.sort(list, new PriceComparator()); // 根据价格排序  
        System.out.println("按书的价格排序:");  
        myprint(list);  

        Collections.sort(list, new CalendarComparator()); // 根据时间排序  
        System.out.println("按书的出版时间排序:");  
        myprint(list);  
    }  

    // 自定义比较器:按书的价格排序  
    static class PriceComparator implements Comparator {  
        public int compare(Object object1, Object object2) {// 实现接口中的方法  
            Book p1 = (Book) object1; // 强制转换  
            Book p2 = (Book) object2;  
            return new Double(p1.price).compareTo(new Double(p2.price));  
        }  
    }  

    // 自定义比较器:按书出版时间来排序  
    static class CalendarComparator implements Comparator {  
        public int compare(Object object1, Object object2) {// 实现接口中的方法  
            Book p1 = (Book) object1; // 强制转换  
            Book p2 = (Book) object2;  
            return p2.calendar.compareTo(p1.calendar);  
        }  
    } 

    // 自定义方法:分行打印输出list中的元素  
    public static void myprint(List<Book> list) {  
        Iterator it = list.iterator(); // 得到迭代器,用于遍历list中的所有元素  
        while (it.hasNext()) {// 如果迭代器中有元素,则返回true  
            System.out.println("\t" + it.next());// 显示该元素  
        }  
    } 
}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

Reference:
Detailed explanation of Collections.sort sorting in java

Java basics - two usages of Collections.sort, simple and clear.

java List sorting Collections.sort()

Comparable and Comparator in Java

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325416622&siteId=291194637