java Collections.sort sorting function usage details

  • 2020-05-19 04:58:38
  • OfStack

Comparator is an interface that overrides compare() and equals() for the price comparison function. If is null, is to use the default order of elements, such as a b, c, d, e, f, g, is a b, c, d, e, f, g so, of course number also is such.

The compare (a,b) method returns a negative integer, a zero, or a positive integer, depending on whether the first parameter is less than, equal to, or greater than the second parameter.

equals (obj) method: returns true only if the specified object is also an Comparator and the same sort is enforced as this Comparator.

Collections. sort (list, new PriceComparator ()); The second parameter of the int method returns a value of type int, which is equivalent to a flag telling the sort method in what order to sort list.

The specific implementation code method is as follows:

Book entity class:


package com.tjcyjd.comparator; 
 
import java.text.DecimalFormat; 
import java.text.SimpleDateFormat; 
import java.util.GregorianCalendar; 
import java.util.Iterator; 
import java.util.TreeMap; 
 
/** 
 *  The book entity class  
 * 
 * @author yjd 
 * 
 */ 
public class Book implements Comparable { //  Definition, Book Class, inherited by default Object class  
  public int id;//  Serial number  
  public String name;//  The name of the  
  public double price; //  The price  
  private String author;//  The author  
  public GregorianCalendar calendar;//  Date of publication  
 
  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; 
  } 
 
  //  Overrides inherit from the parent class Object The way to meet Book Class information description requirements  
  public String toString() { 
    String showStr = id + "\t" + name; //  Defines a string that displays class information  
    DecimalFormat formatPrice = new DecimalFormat("0.00");//  Format the price to two decimal places  
    showStr += "\t" + formatPrice.format(price);//  Formatted price  
    showStr += "\t" + author; 
    SimpleDateFormat formatDate = new SimpleDateFormat("yyyy years MM month dd day "); 
    showStr += "\t" + formatDate.format(calendar.getTime()); //  Formatting time  
    return showStr; //  Returns a string of class information  
  } 
 
  public int compareTo(Object obj) {// Comparable Methods in an interface  
    Book b = (Book) obj; 
    return this.id - b.id; //  According to the book id Compare size for default sort  
  } 
 
  public static void main(String[] args) { 
    Book b1 = new Book(10000, " A dream of red mansions ", 150.86, new GregorianCalendar(2009, 
        01, 25), " Cao xueqin, gao e "); 
    Book b2 = new Book(10001, "3 The historical novel ", 99.68, new GregorianCalendar(2008, 7, 
        8), " Luo guanzhong  "); 
    Book b3 = new Book(10002, " Water margin ", 100.8, new GregorianCalendar(2009, 6, 
        28), " Shy naih-an  "); 
    Book b4 = new Book(10003, " Journey to the west ", 120.8, new GregorianCalendar(2011, 6, 
        8), " Wu chengen "); 
    Book b5 = new Book(10004, " Draco 8 The ministry of ", 10.4, new GregorianCalendar(2011, 9, 
        23), " sohu "); 
    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 Inventory: " + tm.get(key)); 
    } 
  } 
} 

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>(); //  Array sequence  
    Book b1 = new Book(10000, " A dream of red mansions ", 150.86, new GregorianCalendar(2009, 
        01, 25), " Cao xueqin, gao e "); 
    Book b2 = new Book(10001, "3 The historical novel ", 99.68, new GregorianCalendar(2008, 7, 
        8), " Luo guanzhong  "); 
    Book b3 = new Book(10002, " Water margin ", 100.8, new GregorianCalendar(2009, 6, 
        28), " Shy naih-an  "); 
    Book b4 = new Book(10003, " Journey to the west ", 120.8, new GregorianCalendar(2011, 6, 
        8), " Wu chengen "); 
    Book b5 = new Book(10004, " Draco 8 The ministry of ", 10.4, new GregorianCalendar(2011, 9, 
        23), " sohu "); 
    list.add(b1); 
    list.add(b2); 
    list.add(b3); 
    list.add(b4); 
    list.add(b5); 
    // Collections.sort(list); // There is no default comparator and cannot sort  
    System.out.println(" The elements in an array sequence :"); 
    myprint(list); 
    Collections.sort(list, new PriceComparator()); //  Sort by price  
    System.out.println(" Sort by the price of the book :"); 
    myprint(list); 
    Collections.sort(list, new CalendarComparator()); //  Sort by time  
    System.out.println(" Sort the books by the time they were published :"); 
    myprint(list); 
  } 
 
  //  Custom method: print out the branch list The elements in the  
  public static void myprint(List<Book> list) { 
    Iterator it = list.iterator(); //  Get the iterator for traversing list All the elements in  
    while (it.hasNext()) {//  Returns if there is an element in the iterator true 
      System.out.println("\t" + it.next());//  Display the element  
    } 
  } 
 
  //  Custom comparator: sort by book price  
  static class PriceComparator implements Comparator { 
    public int compare(Object object1, Object object2) {//  Implement the methods in the interface  
      Book p1 = (Book) object1; //  Casts.  
      Book p2 = (Book) object2; 
      return new Double(p1.price).compareTo(new Double(p2.price)); 
    } 
  } 
 
  //  Custom comparator: sort the book by the time it was published  
  static class CalendarComparator implements Comparator { 
    public int compare(Object object1, Object object2) {//  Implement the methods in the interface  
      Book p1 = (Book) object1; //  Casts.  
      Book p2 = (Book) object2; 
      return p2.calendar.compareTo(p1.calendar); 
    } 
  } 
} 

Related articles: