“So verwenden Sie Java 8 -Komparator” Code-Antworten

So verwenden Sie Java 8 -Komparator

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

So verwenden Sie Java 8 -Komparator

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

Ähnliche Antworten wie “So verwenden Sie Java 8 -Komparator”

Fragen ähnlich wie “So verwenden Sie Java 8 -Komparator”

Weitere verwandte Antworten zu “So verwenden Sie Java 8 -Komparator” auf Java

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen