List集合排序Demo
import com. google. common. collect. Lists ;
import lombok. AllArgsConstructor ;
import lombok. NoArgsConstructor ; import java. util. * ;
public class ListOrderDemo { public static void main ( String [ ] args) { List < String > list = Lists . newArrayList ( "1" , "3" , "2" ) ; String [ ] array = list. toArray ( new String [ ] { } ) ; System . out. println ( Arrays . toString ( array) ) ; list. sort ( String :: compareTo ) ; System . out. println ( list) ; list. sort ( ( o1, o2) -> o1. compareTo ( o2) ) ; System . out. println ( list) ; list. sort ( new Comparator < String > ( ) { @Override public int compare ( String o1, String o2) { return o1. compareTo ( o2) ; } } ) ; System . out. println ( list) ; list. sort ( Comparator . reverseOrder ( ) ) ; System . out. println ( list) ; list. sort ( ( o1, o2) -> o2. compareTo ( o1) ) ; System . out. println ( list) ; list. sort ( new Comparator < String > ( ) { @Override public int compare ( String o1, String o2) { return o2. compareTo ( o1) ; } } ) ; System . out. println ( list) ; List < Order > orders = new ArrayList < > ( ) ; orders. add ( new Order ( "4" , 1 ) ) ; orders. add ( new Order ( "3" , 2 ) ) ; orders. add ( new Order ( "2" , 2 ) ) ; orders. add ( new Order ( "1" , 3 ) ) ; orders. sort ( Order :: compareTo ) ; System . out. println ( orders) ; orders. sort ( ( o1, o2) -> o1. compareTo ( o2) ) ; System . out. println ( orders) ; Collections . sort ( orders) ; System . out. println ( orders) ; } @NoArgsConstructor @AllArgsConstructor public static class Order implements Comparable < Order > { private String name; private Integer age; @Override public int compareTo ( Order o) { if ( Objects . equals ( this . age, o. age) ) { return this . name. compareTo ( o. name) ; } return this . age. compareTo ( o. age) ; } @Override public String toString ( ) { return "{\"age: \"" + this . age + ", \"name:\"" + this . name + "}" ; } }
}