JAVA Collections utility class sort of sorting method

  • 2020-05-12 02:40:23
  • OfStack

This question introduces two sort() methods of the Collections tool class, as follows:

1. Two sort() methods of the Collections tools class

Format 1: public static < T extends Comparable < ? super T > > void sort(List < T > list)

Description: generics in this method < T > All are subclasses of the Comparable interface, which means that only data of the Comparable interface subclass type can be collated. If other types of data are to be collated, you must inherit the Comparable interface and

Override the equals() and compareTo() methods. For example, String class and Integer class are subclasses of Comparable interface and can be sorted, while basic types cannot be sorted by sort. The comparison item is specified within the class

Format 2: public static < T > void sort(List < T > list, Comparator < ? super T > c)

Note: this method specifies the comparison method Comparator < ? super T > c, or c, must implement Comparator < ? super T > Interface that overrides the compareTo() method to specify the comparison item. Comparison items are specified outside the class, which is flexible

Example 2.

Common methods for getting strings and Numbers in the example:


/**
   *  Generate random   A string that does not repeat  : number  Number of generated strings 
   */
  public static List<String> generateString(int number) {
    List<String> listString = new ArrayList<>(); //  Used to store the return value 
    List<Integer> length = null; //  String length 
    StringBuffer sb = new StringBuffer(); //  Intermediate variable 
    int control = 0; //  Control the number of 
    String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h",
        "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
        "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
        "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
        "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
        "U", "V", "W", "X", "Y", "Z" };
    while (true) {
      //  Control over 
      if ( control==number ) {
        break;
      }
      //  Generate a random number, generate 36 bit 2aaab761-4341-4968-aceb-3861ee3824b2 UUID Type data 
      String uuid = UUID.randomUUID().toString().replace("-", "");
      sb.setLength(0);
      //  Gets the random string length, which is not 0
      do {
        length = getDiffNo(1, 11);
      } while ( length.get(0)==0 );
      //  Patchwork string 
      for (int i=0; i<length.get(0); i++) {
        String str = uuid.substring(i*3, (i*3+3));
        // will str String conversion to 16 Base, get its value 
        int x = Integer.parseInt(str, 16);
        // Take more than: x % 0x3E--0x3E = 3*16 + 14 = 62,  Among them chars There are 62 A character 
        sb.append(chars[x % 0x3E]);
      }
      listString.add(sb.toString());
      control++;
    }
    return listString;
  }

  /**
   *  Generate random Numbers that do not repeat  :n Number of generated  max Generate range 
   */
  public static List<Integer> getDiffNo(int n, int max) {
    //  generate  [0-n]  A random number that does not repeat 
    // list  To hold these random Numbers 
    List<Integer> list = new ArrayList<>();
    Random random = new Random();
    Integer k;
    for (int i=0; i<n; i++) {
      do {
        k = random.nextInt(max);
      } while (list.contains(k));
      list.add(k);
    }
    return list;
  }

1. Sort List of Integer generics


/**
   * 1. through Collections.sort() Methods, Integer The generic List Sort; 
   *  create 1 a Integer The generic List And insert it into the 10 a 100 Not repeating random integers within,   call Collections.sort() Method sorts it 
   * 2. Sorting rule: first number, then letter, number 0-9 , the letter A-Z a-z The order of 
   */
  public void listIntegerSort() {
    //  insert 10 a 100 Do not repeat random integers within 
    List<Integer> integerList = getDiffNo(10, 100);
    System.out.println("------------- Before ordering --------------");
    for (Integer integer : integerList) {
      System.out.println(" Chemical element: " + integer);
    }
    Collections.sort(integerList);
    System.out.println("---------------- After ordering -------------------");
    for (Integer integer : integerList) {
      System.out.println(" Chemical element: " + integer);
    }
  }

2. Rank List of String generics


/**
   * 1. right String The generic List Sort;   create String The generic List , add out of order String Elements, 
   *  call sort Method to output the sorted order again 
   */
  public void listStringSort() {
    List<String> stringList = new ArrayList<String>();
    stringList.add("eipJlcx");
    stringList.add("WvQRufC");
    stringList.add("J");
    stringList.add("HdaU2G");
    stringList.add("M0WswHD3");
    System.out.println("------------ Before ordering -------------");
    for (String string : stringList) {
      System.out.println(" Chemical element: " + string);
    }
    Collections.sort(stringList);
    System.out.println("-------------- After ordering ---------------");
    for (String string : stringList) {
      System.out.println(" Chemical element: " + string);
    }
  }

/**
   *  right String The generic List I'm going to sort it, and I'm going to randomly generate it 10 The length of the string is in 10 within 
   */
  public void listStringRandomSort() {
    //  Generate a random string 
    List<String> listString = generateString(10);
    System.out.println("-------------- Before ordering ---------------");
    for (String integer : listString) {
      System.out.println(" Chemical element: " + integer);
    }
    //  The sorting 
    Collections.sort(listString);
    System.out.println("---------------- After ordering ------------------");
    for (String integer : listString) {
      System.out.println(" Chemical element: " + integer);
    }
  }

3. Sort List for other types of generics

Course class implements


/**
 *  Course class 
 * @author Administrator
 *
 */
public class Course {
  public String id;
  public String name;
  public Course(String id, String name) {
    this.id = id ;
    this.name = name;
  }
  public Course() {
  }
  
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (!(obj instanceof Course))
      return false;
    Course other = (Course) obj;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    return true;
  }
}

The Student class implements the Comparable interface and sets the comparator inside the class


import java.util.HashSet;
import java.util.Set;

/**
 *  Students in class 
 * @author Administrator
 *
 */
public class Student implements Comparable<Student> {
  public String id;
  public String name;
  public Set<Course> courses;
  
  public Student(String id, String name) {
    this.id = id;
    this.name = name;
    this.courses = new HashSet<Course>();
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (!(obj instanceof Student))
      return false;
    Student other = (Student) obj;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    return true;
  }

  @Override
  public int compareTo(Student o) { //  Set up the ID To compare the item 
    // TODO Auto-generated method stub
    return this.id.compareTo(o.id);
  }
}

Implement the Comparator interface and set the comparator outside the class


import java.util.Comparator;
public class StudentComparator implements Comparator<Student> {

  @Override
  public int compare(Student o1, Student o2) {
    // TODO Auto-generated method stub
    return o1.name.compareTo(o2.name);
  }
}

Compare Student class


/**
   *  For other types of generics List Sort by Student As an example. 
   */
  public void listComparatorSort() {
    List<Student> studentList = new ArrayList<Student>();
    List<Integer> list = getDiffNo(4, 1000);

    studentList.add(new Student(list.get(0) + "", "Mike"));
    studentList.add(new Student(list.get(1) + "", "Angela"));
    studentList.add(new Student(list.get(2) + "", "Lucy"));
    studentList.add(new Student(1000 + "", "Beyonce"));
    System.out.println("-------------- Before ordering ---------------");
    for (Student student : studentList) {
      System.out.println(" Student: " + student.id + ":" + student.name);
    }
    //  implementation Comparator<T> Interface, Settings ID Compare the way 
    Collections.sort(studentList);
    System.out.println("---------------- In accordance with the ID After ordering ------------------");
    for (Student student : studentList) {
      System.out.println(" Student: " + student.id + ":" + student.name);
    }

    //  implementation Comparator<T> Interface that sets the specific comparison mode to name Comparison sort 
    Collections.sort(studentList, new StudentComparator());
    System.out.println("---------------- Sorted by name -----------------");
    for (Student student : studentList) {
      System.out.println(" Student: " + student.id + ":" + student.name);
    }
  }


Related articles: