
1. preface
Recently, collection sorting (based on Java 8) was used. Now I can use Stream Use it Stream , it smells so fragrant! Sort can be written as follows:
List<People> peoples = new ArrayList<>();
//omitted in the middle
//Sort by age from small to large
peoples.sort(Comparator.comparing(People::getAge));
Sorting here uses a key interface java.util.Comparator
。Sort comparison is a frequent requirement in business, so it is necessary for us to study this interface.
2. Comparator concept
Comparator
Is a functional interface. It is often used to sort collections that do not have natural sorting, such as Collections.sort
or Arrays.sort
。Or declare collations for certain ordered data structures, such as TreeSet
、TreeMap
。That is, this interface is mainly used for sorting collections.
3. Methods in Comparator
Comparator
As a functional interface, there is only one abstract method, but it has many default methods. Let's get to know these methods.
3.1 compare abstract method
asComparator
The only abstract way,int compare(T o1,T o2)
Compare the sizes of the two parameters and return a negative integer, zero, and positive integer, which respectively represent o1<o2
、o1=o2
、o1>o2
, usually return separately -1
、0
or 1
。Pseudo-expression:
//Enter two objects of the same type and output an int number of the comparison result
(x1,x2)-> int
To implement this method, the following must be noted:
- must ensure
compare(x,y)
andcompare(y,x)
The sum of the values of must be 0 。 - You must ensure that the order of comparisons is transitive if
compare(x,y)>0
andcompare(y,z)>0
thencompare(x,z)>0
。 - if present
compare(x,y)=0
, then forz
In terms of existencecompare(x, z)==compare(y, z)
。
However, there are no strict requirements
(compare(x, y)==0) == (x.equals(y))
。In general, any Comparator implementation that violates this condition should clearly point out this fact.
3.2 Comparing series methods
from Java 8 At first,Comparator
Provides a series of static methods and assigns them through a functional style Comparator
More powerful and convenient functions, let's call them for the time being comparing
series of methods.
public static <T, U> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor,
Comparator<? super U> keyComparator)
{
Objects.requireNonNull(keyExtractor);
Objects.requireNonNull(keyComparator);
return (Comparator<T> & Serializable)
(c1, c2) -> keyComparator.compare(keyExtractor.apply(c1),
keyExtractor.apply(c2));
}
This method is the basic method of this series of methods. Does it seem difficult to understand? Let's analyze this method. Its two parameters are functional interfaces.
the first parameter Function<? super T, ? extends U> keyExtractor
Indicates that input one is T
Type object, outputting a U
Type object, for example, enter a People
Object returns its age Integer
Value:
// people -people.getAge(); converts to the following method reference
Function<People, Integer> getAge = People::getAge;
the second parameter keyComparator
It is easy to understand and expresses the comparison rules used.
on c1
,c2
According to the first parameter keyExtractor
The rules provided are used to extract characteristics, and then the second parameterkeyComparator
Compare these two characteristics. The following formula can actually be summarized as 3.1 the (x1,x2)-> int
(c1, c2) -> keyComparator.compare(keyExtractor.apply(c1),
keyExtractor.apply(c2))
Comparator
&Serializable is a new feature in Java 8: satisfies both type constraints
After understanding this method, other methods in this series will be easy to understand and will not be repeated here. currently comparing
The series of methods are more widely used. Let's give some examples:
List<People> peoples = new ArrayList<>();
// ………………
//Sort by age from lowest to highest
peoples.sort(Comparator.comparing(People::getAge));
//Sort by age from highest to lowest
peoples.sort(Comparator.comparing(People::getAge, (x, y) -> -x.compareTo(y)));
You can also use
java.util.Collections
orStream
Provided sorting method to useComparator
。
4. summary
today Comparator
A simple analysis is performed, which is used to build rules for sorting collections and is very useful in daily development. Next article We will test another interface that is very similar to it Comparable
Please pay attention to the analysis.
Comments0