Summary of sorting of collections and arrays in Java

  • 2020-04-01 03:41:06
  • OfStack

By convention, you should use as many libraries as you can when programming in Java, and you can write your own sorting methods or frameworks, but how many people can write better than the JDK? Another benefit of using existing classes is that the code is easy to read and maintain, and this article focuses on sorting arrays and various Collection containers using existing class libraries. (some of the examples in this article are from Java Developers Almanac 1.4.)

The first thing to know is that there are two classes :java.util.Arrays and java.util.Collections(note the difference between Collections and Collections).Collections are the top-level interface to the Collections framework, while Collections contain many static methods. We use Arrays to sort Arrays and Collections to sort binding framework containers such as ArraysList,LinkedList, and so on.

Import java.util.* and other shell code, such as classes and static main methods, are included in the examples.

Sort the array

For example, there is an integer array:


int[] intArray = new int[] {4, 1, 3, -23};

So how do we sort this? Are you thinking about quicksort algorithms at this point? Take a look at the following implementation:

import java.util.*; 
public class Sort{ 
    public static void main(String[] args){ 
        int[] intArray = new int[] {4, 1, 3, -23}; 
        Arrays.sort(intArray); 
    } 
}

So we sort the intArray in ascending order using sort(), the static method of Arrays, and now the array is {-23,1,3,4}.

If it is a character array:


String[] strArray = new String[] {"z", "a", "C"};

We use:

Arrays.sort(strArray);

The result is {C,a,z},sort() sort in ascending order according to the natural order of the elements. If you want to be case-insensitive, write:

Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);

Of course, we can also specify a section of the array to be sorted. For example, if we want to sort the part of the array in the following table 0-2 (assuming the array length is greater than 3), we can use:

Arrays.sort(strArray,0,2);

This way, we only sort the first three elements without affecting the rest.

And of course some people think, how do I sort in descending order? There is one sort method among many


sort(T[] a, Comparator<? super T> c)

We can use the Comparator to get an anti-order Comparator, which will be explained later. IntArray [] is an example:

Arrays.sort(intArray,Comparator.reverseOrder());

So, we get {4,3,1,-23}. If you don't want to change the original code, we can also use:

Collections.reverse(Arrays.asList(intArray));

Gets the reverse order of the array. The result is also 4,3,1,-23}.

Instead of having primitive data types (primtive type) or arrays of String types, we now have arrays of objects. The natural order of the array is unknown, so we need to implement the Comparable interface for this class. For example, we have a Name class:


class Name implements Comparable<Name>{ 
    public String firstName,lastName; 
    public Name(String firstName,String lastName){ 
        this.firstName=firstName; 
        this.lastName=lastName; 
    } 
    public int compareTo(Name o) {          //Implementation interface & NBSP; < br / >         int lastCmp=lastName.compareTo(o.lastName); 
        return (lastCmp!=0?lastCmp:firstName.compareTo(o.firstName)); 
    }     
    public String toString(){                //Convenient for output testing & NBSP; < br / >         return firstName+" "+lastName; 
    } 
}

So, when we sort this array of objects, we compare lastName, then we compare firstName and we get the order of the two objects, just like we did in compareTo(Name o). Try it with a program:

import java.util.*; 
 public class NameSort { 
     public static void main(String[] args) { 
         Name nameArray[] = { 
            new Name("John", "Lennon"), 
            new Name("Karl", "Marx"), 
            new Name("Groucho", "Marx"), 
            new Name("Oscar", "Grouch") 
        };
        Arrays.sort(nameArray); 
        for(int i=0;i<nameArray.length;i++){ 
            System.out.println(nameArray[i].toString()); 
        } 
    } 
}

The results were as we had hoped:

Oscar Grouch 
John Lennon 
Groucho Marx 
Karl Marx

Sort the collection framework

If you already understand arrays.sort () to sort Arrays, the collections framework is used in much the same way. I just replaced Arrays with Collections, noting that Collections are a class and Collections are an interface, but they have completely different meanings despite the fact that they are just one "s" away.

Suppose you have a linked list like this:


LinkedList list=new LinkedList(); 
list.add(4); 
list.add(34); 
list.add(22); 
list.add(2);

We only need to use:

Collections.sort(list);

You can sort the elements in ll from small to large, and the result is:

[2, 4, 22, 34]

If the LinkedList element is a String, it will be sorted from small to large, just like the basic data type.

If you want to implement reverse sort, that is, from to small sort:


Collections.sort(list,Collectons.reverseOrder());

If the elements in the LinkedList are custom objects and you can implement the Comparable interface like the Name object above, you can have collection.sort () sort for you.

If you want to sort an object the way you want, you can use


sort(List<T> list, Comparator<? super T> c)

This method sorts. Before I give you an example, let me show you how to use the Comparator and the Comparable interface format:

public interface Comparator<T> { 
    int compare(T o1, T o2); 
}

Int compare(T o1,T o2) in the Comparator is actually written the same way as compareTo() in Comparable. In the Name class above, we start with LastName, which is a western custom. In China, we want to start with fristName, but we don't want to change the original code.

final Comparator<Name> FIRST_NAME_ORDER=new Comparator<Name>() { 
    public int compare(Name n1, Name n2) { 
         int firstCmp=n1.firstName.compareTo(n2.firstName); 
         return (firstCmp!=0?firstCmp:n1.lastName.compareTo  
                 (n2.firstName)); 
    } 
};

We'll have a Comparator FIRST_NAME_ORDER that we can customize.

Convert the array of names from the previous example to List:


List<Name> list=Arrays.asList(nameArray); 
Collections.sort(list,FIRST_NAME_ORDER);

Thus we successfully set the sort using our own defined comparator.


Related articles: