“Как использовать Java 8 компаратор” Ответ

Как использовать Java 8 компаратор

public class Apple implements Comparable<Apple> {
    private int id;
    private Color color;
    private int weight;
    //constructor
    public Apple(int id, Color color, int weight) {
        this.id = id;
        this.color = color;
        this.weight = weight;
    }  
   // Here we implement the compareTo() method of the Comparable interface.    
    @Override
    public int compareTo(Apple apple) {
        return this.getColor().compareTo(apple.getColor());
    }
    // getters / setters and toString()
    //
    //
    enum Color {
        RED, GREEN
    }
}
Zany Zebra

Как использовать 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

Ответы похожие на “Как использовать Java 8 компаратор”

Вопросы похожие на “Как использовать Java 8 компаратор”

Больше похожих ответов на “Как использовать Java 8 компаратор” по Java

Смотреть популярные ответы по языку

Смотреть другие языки программирования