Home Java javaTutorial Detailed explanation of examples of Collections.sort sorting in Java

Detailed explanation of examples of Collections.sort sorting in Java

May 02, 2017 am 11:57 AM

Comparator is an interface that can override the compare() and equals() methods. Next, this article will introduce you to Collections.sort sorting in Java. Friends who need it can refer to it

Comparator It is an interface that can override the two methods compare() and equals() for price comparison function; if it is null, the default order of elements is used, such as a, b, c, d, e, f, g. It's a, b, c, d, e, f, g. Of course, the numbers are also like this.

compare(a,b) method: Returns a negative integer, 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 a Comparator and enforces the same ordering as this Comparator.

The second parameter of Collections.sort(list, new PriceComparator()); returns an int value, which is equivalent to a flag that tells the sort method in what order to sort the 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; 
/** 
 * 书实体类 
 * 
 * @author yjd 
 * 
 */ 
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)); 
    } 
  } 
}
Copy after login

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); 
  } 
  // 自定义方法:分行打印输出list中的元素 
  public static void myprint(List<Book> list) { 
    Iterator it = list.iterator(); // 得到迭代器,用于遍历list中的所有元素 
    while (it.hasNext()) {// 如果迭代器中有元素,则返回true 
      System.out.println("\t" + it.next());// 显示该元素 
    } 
  } 
  // 自定义比较器:按书的价格排序 
  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); 
    } 
  } 
}
Copy after login

The above is the detailed content of Detailed explanation of examples of Collections.sort sorting in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1280
29
C# Tutorial
1257
24
Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

How to configure the character set and collation rules of MySQL How to configure the character set and collation rules of MySQL Apr 29, 2025 pm 04:06 PM

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

How to rename a database in MySQL How to rename a database in MySQL Apr 29, 2025 pm 04:00 PM

Renaming a database in MySQL requires indirect methods. The steps are as follows: 1. Create a new database; 2. Use mysqldump to export the old database; 3. Import the data into the new database; 4. Delete the old database.

How to implement singleton pattern in C? How to implement singleton pattern in C? Apr 28, 2025 pm 10:03 PM

Implementing singleton pattern in C can ensure that there is only one instance of the class through static member variables and static member functions. The specific steps include: 1. Use a private constructor and delete the copy constructor and assignment operator to prevent external direct instantiation. 2. Provide a global access point through the static method getInstance to ensure that only one instance is created. 3. For thread safety, double check lock mode can be used. 4. Use smart pointers such as std::shared_ptr to avoid memory leakage. 5. For high-performance requirements, static local variables can be implemented. It should be noted that singleton pattern can lead to abuse of global state, and it is recommended to use it with caution and consider alternatives.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence? What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence? May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

What are the advantages of using Java for web applications that need to run on different servers? What are the advantages of using Java for web applications that need to run on different servers? May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How to set the rotation effect of HTML elements How to set the rotation effect of HTML elements Apr 30, 2025 pm 02:42 PM

How to set the rotation effect of an element in HTML? It can be achieved using CSS and JavaScript. 1. The transform property of CSS is used for static rotation, such as rotate(45deg). 2. JavaScript can dynamically control rotation, which is implemented by changing the transform attribute.

See all articles