“Jak używać komparatora Java 8” Kod odpowiedzi

Jak używać komparatora 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

Jak używać komparatora 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

Odpowiedzi podobne do “Jak używać komparatora Java 8”

Pytania podobne do “Jak używać komparatora Java 8”

Więcej pokrewnych odpowiedzi na “Jak używać komparatora Java 8” w Java

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu