当前位置:网站首页>Comparator sort functional interface

Comparator sort functional interface

2022-06-24 13:06:00 51CTO

Comparator Is a functional interface , This function is mainly used to customize sorting rules , Other functions are not recorded here , Just record how you sort :

The current common sorting methods :

Array sorting 、 Collection sorting 、 Convert collection to stream sort

      
      
public class sortTest {
public static void main( String[] args) {
List < User > usersList = new ArrayList <>(){
{
for( int i = 0; i < 3; i ++) {
add( new User( "lxc" + i, 20 + i));
}
}
};
// Mode one -> Array utility class :Arrays.sort(T[] a, Comparator<? super T> c);
// Mode two -> A collection of stream() Method :new ArrayList<>().stream().sorted(Comparator<? super T> comparator);
// Mode two -> Collection tool class :
Collections. sort( usersList, new Comparator < User >() {
@Override
public int compare( User o1, User o2) {
// In reverse order
return o2. getAge() - o1. getAge();
// positive sequence
return o1. getAge() - o2. getAge();
}
});
System. out. println( JSON. toJSONString( usersList, SerializerFeature. PrettyFormat));
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

Comparator Sort functional interface _json

  Cases in actual development :

If the front and back ends are separated from the frame , The front desk excel When downloading template , The backend is actually a new one excel, Then fill in the data , internals : Get every field in the entity class to be exported through reflection , Add to list In the list , Loop traversal list list , The with @Excel Annotated fields and @Excel Attributes in the annotation are added to One Object[] Go to... In the array , And then put Object[] Array added to fields Go to... In the list , Finally, convert the list into a stream , Sort .

Comparator Sort functional interface _java_02

Comparator Sort functional interface _java_03


原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241233194319.html