“Comment utiliser Java 8 Comparator” Réponses codées

Comment utiliser Java 8 Comparator

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

Comment utiliser Java 8 Comparator

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

Réponses similaires à “Comment utiliser Java 8 Comparator”

Questions similaires à “Comment utiliser Java 8 Comparator”

Plus de réponses similaires à “Comment utiliser Java 8 Comparator” dans Java

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code