Initial code:
An Apple class
Public classapple{String color; Integer size; Float weight; PublicApple () {} PublicApple (String color, Integer size, Float weight) { This. color =color; This. Size =size; This. Weight =weight; } PublicString GetColor () {returncolor; } Public voidsetcolor (String color) { This. color =color; } PublicInteger GetSize () {returnsize; } Public voidsetSize (Integer size) { This. Size =size; } PublicFloat getweight () {returnweight; } Public voidsetweight (Float weight) { This. Weight =weight; } @Override PublicString toString () {return"apple{" + "weight=" + weight + ", size=" + size + ", color=" + Color + ‘}‘; }}
View Code
The main function is assigned a value of one print
Public Static voidMain (string[] args) {List<Apple> applelist =NewArraylist<>(); Applelist.add (NewApple ("Red", 111, 333F)); Applelist.add (NewApple ("Yellow", 333, 222F)); Applelist.add (NewApple ("Blue", 222, 888F)); Applelist.add (NewApple ("Black", 555, 777F)); Applelist.add (NewApple ("Pink", 444, 111F)); Applelist.add (NewApple ("Green", 666, 444F)); } Private Static<T>voidForEach (list<t>list) { for(Object vo:list) {System.out.println (vo.tostring ()); } }
First Level: Pass code
Apple class implements comparator replication compare
Public class Implements Comparator<apple> { String color; Integer size; Float weight; @Override publicint Compare (Apple O1, Apple O2) { return o1.getsize (). CompareTo (O2.getsize ()); } ...}
Applelist.sort (new Apple ()); ForEach (applelist);
Printing results:
Second Level: Anonymous class
Apple class restore does not implement comparator
Applelist.sort (new comparator<apple>() { @Override publicint Compare (Apple O1, Apple O2) { return o1.getsize (). CompareTo (O2.getsize ()); } ); ForEach (applelist);
Print the same result
Level three: Using lambda expressions
The same way of passing code. Lightweight notation
Applelist.sort (Apple o1,apple O2), o1.getsize (). CompareTo (O2.getsize ())); ForEach (applelist);
Can you be a little more concise? Yes.
The Java compiler can infer the type of an expression parameter based on the context of the lambda, so you can omit the parameter type when writing a lambda
Applelist.sort (O1,O2), o1.getsize (). CompareTo (O2.getsize ())); ForEach (applelist);
Can you be a little more concise? Yes.
Comparator has a comparing static helper method that can accept a function to extract the comparable key value and generate a Comparator object
Applelist.sort (Comparator.comparing ((a),a.getsize ())); ForEach (applelist);
Level fourth: Using method references
Applelist.sort (comparator.comparing (apple::getsize)); ForEach (applelist);
Method references are simply LAMPBDA syntax sugars that involve a single method, and are used in the same way as calling static methods in PHP, like: methods.
List Sort Advanced