Java collection, array sorting

In the process of normal development, we often encounter the need to sort the elements of arrays and collections according to rules. This paper records the possible situations and related complete code examples in the development process.

Knowledge points

  • Compatible < T > interface
    If the object implements the interface, the compareTo method must be overridden. If the object implements the interface, the object has sorting functions, such as String, Integer, etc.
  • Comparator < T > interface
    To implement a custom sorter, you need to implement this interface. When a class does not have sorting function or the existing sorting function is not enough to support your needs, it is time for the user-defined sorter to appear. For example, the built-in sorting of String implements sorting by character order. What do I do if I want to sort by String length? At this point, you can customize the object that implements Comparator.
  • Array (such as String []) sorting uses Arrays.sort
  • Use Collections.sort to sort collections (such as list < T >)

Example

1. Example of default String sorting

1.1 array sorting usage

String[] strArr = new String[]{"zhangsan","lisi","wangwu"};
//Array is sorted by character ascending by default
Arrays.sort(strArr);
System.out.println("Sort alphabetically by default:");
for (String str:strArr) {
    System.out.println(str);
}

1.2 set sorting usage

List<String> strList = new ArrayList<>();
strList.add("zhangsan");
strList.add("lisi");
strList.add("wangwu");
//Set is sorted by character ascending by default
Collections.sort(strList);
System.out.println("Sort alphabetically by default:");
for (String str:strList) {
    System.out.println(str);
}
  • The above two examples are output:

2. Custom sorter, String array in reverse order of String length

  • Create a custom sorter StringComparator
package com.simon.interfacedemo.sortdemo.stringdemo;

import java.util.Comparator;
/**
 * @Description: By implementing the Comparator interface, the user-defined sorting can be realized
 */
public class StringComparator implements Comparator<String>{
    /**
     * Sort by string length in descending order
     */
    @Override
    public int compare(String o1, String o2) {
        return o1.length() > o2.length() ? -1 : 1;
    }
}

2.1 array using StringComparator sorter

String[] strArr = new String[]{"zhangsan","lisi","wangwu"};
//Custom sort, ascending by string length
Arrays.sort(strArr,new StringComparator());
System.out.println("Custom sort, sort by string length descending:");
for (String str:strArr) {
    System.out.println(str);
}

2.2 use StringComparator sorter for collection

List<String> strList = new ArrayList<>();
strList.add("zhangsan");
strList.add("lisi");
strList.add("wangwu");
//Custom sort, descending by string length
Collections.sort(strList,new StringComparator());
System.out.println("Custom sort, sort by string length descending:");
for (String str:strList) {
    System.out.println(str);
}
  • The above two examples are output:

3. The user-defined class implements the compatible interface, so that the class has sorting function

  • Customize the Student class, implement the compatible interface, override the compareTo method, and sort by age in ascending order
public class Student implements Comparable<Student>{

    private String name;
    private Integer age;

    public Student(String name,Integer age){
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    /**
     * Implement compareTo interface method, in ascending order of age.
     * @param o
     * @return Return 1: greater than, 0: equal to, - 1: less than
     */
    @Override
    public int compareTo(Student o) {
        return Integer.compare(age,o.age);
    }

   /**
     * Rewriting toString method is convenient for System.out.println to print out detailed information.
     */
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

3.1 Student array is sorted in ascending order of age

Student[] students = new Student[3];
students[0] = new Student("zhangsan",30);
students[1] = new Student("lisi",28);
students[2] = new Student("wangwu",33);

System.out.println("adopt student Default sort of implementation, based on age Sort ascending:");
Arrays.sort(students);
for (Student student : students) {
    System.out.println(student);
}

3.2 Student sets are sorted in ascending age order

List<Student> studentList = new ArrayList<>();
studentList.add(new Student("zhangsan",30));
studentList.add(new Student("lisi",28));
studentList.add(new Student("wangwu",33));
System.out.println("adopt student Default sort of implementation, based on age Sort ascending:");
Collections.sort(studentList);
for (Student student : studentList) {
    System.out.println(student);
}
  • The above two examples are output:

4. User defined sorter, sorted by Student's name length in ascending order

  • Create a custom sorter, StudentComparator
package com.simon.interfacedemo.sortdemo.studentdemo;

import java.util.Comparator;
/**
 * @Description: By implementing the Comparator interface, the user-defined sorting can be realized
 */
public class StudentComparator implements Comparator<Student>{
    /**
     * Sort by name length in ascending order
     */
    @Override
    public int compare(Student o1, Student o2) {

        return o1.getName().length() > o2.getName().length() ? 1 : -1;
    }
}

4.1 using student comparator sorter for array

Student[] students = new Student[3];
students[0] = new Student("zhangsan",30);
students[1] = new Student("lisi",28);
students[2] = new Student("wangwu",33);

System.out.println("Sort by user-defined sorter, sort by name length:");
Arrays.sort(students,new StudentComparator());
for (Student student : students) {
    System.out.println(student);
}

4.2 using student comparator sorter for collection

List<Student> studentList = new ArrayList<>();
studentList.add(new Student("zhangsan",30));
studentList.add(new Student("lisi",28));
studentList.add(new Student("wangwu",33));

System.out.println("Sort by the user-defined sorter according to the name length:");
Collections.sort(studentList,new StudentComparator());
for (Student student : students) {
    System.out.println(student);
}
  • The above two examples are output:

Follow-up

  • The above lists the array and collection sorting methods that may be used in the actual development. Using lambda can also be more simplified and summarized later.
  • All of the above examples are available through My GitHub Get the complete code, Click to get

Tags: Java less Lambda github

Posted on Fri, 06 Mar 2020 19:50:30 -0800 by oldschool