The source code is for testing only and should not be used commercially. The source code comes from the Internet. If there is any infringement, please contact me to remove it.
Java 集合排序规则接口 Comparator

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 TreeSetTreeMap 。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<o2o1=o2o1>o2, usually return separately -10 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 ensurecompare(x,y) andcompare(y,x) The sum of the values of must be 0
  • You must ensure that the order of comparisons is transitive ifcompare(x,y)>0 andcompare(y,z)>0 then compare(x,z)>0
  • if present compare(x,y)=0, then for z In terms of existence compare(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 comparingseries 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 keyComparatorIt 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 parameterkeyComparatorCompare 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 or Stream Provided sorting method to useComparator

4. summary

today ComparatorA 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.

read more
Resource download
PriceFree
Customer Service QQ: 138338438
Original link:https://bcbccb.cn/en/4615.html, please indicate the source for reprinting.
1

Comments0

量推3二开新UI房卡棋牌组件+文本教程
Volume push 3 Second open new UI room card chess and card components + text tutorial
Someone bought it 1 minute ago Go and have a look

Site Announcements

The source code (theme/plug-in/application source code) and other resources provided by this site are only for learning and exchange

Commercial use is prohibited, otherwise all consequences will be borne by the downloading user!

Some resources are collected or copied online. If they infringe on your legitimate rights and interests, please write to us.

Currently, members have a big reward, and the current price for a lifetime member is 299 gold coins.Recent price adjustments

Join quickly, opportunities wait for no one! immediately participated in

Captcha

Fast login to social accounts

en_USEnglish