Como usar o comparador Java 8
import static java.util.Comparator.comparing;
public class Main {
public static void main(String[] args) {
List<Apple> applesList = getApples();
1. //Using comparator with a custom class that implements
//the Comparator Interface.
System.out.println("\n//Using comparator with a custom class ");
applesList.sort(new ColorComparator()
.reversed());
applesList.forEach(System.out::println);
2. //Using the comparator in a functional style to compare
// apples based on a single attribute, the color
System.out.println("\nComparing apples based on the color ");
applesList.sort(comparing(Apple::getColor)
.reversed());
applesList.forEach(System.out::println);
3. //Using the comparator in a functional style to compare
// apples based on multiple attributes, the color and the weight.
System.out.println("\nComparing apples based on the color and the weight");
applesList.sort(comparing(Apple::getColor)
.thenComparing(Apple::getWeight)
.reversed());
applesList.forEach(System.out::println);
}
private static List<Apple> getApples() {
List<Apple> apples = new ArrayList<>();
apples.add(new Apple(1, Apple.Color.RED, 35));
apples.add(new Apple(2, Apple.Color.GREEN, 23));
apples.add(new Apple(3, Apple.Color.GREEN, 27));
apples.add(new Apple(4, Apple.Color.RED, 30));
apples.add(new Apple(5, Apple.Color.GREEN, 35));
apples.add(new Apple(6, Apple.Color.RED, 23));
return apples;
}
}
Zany Zebra