Collections.sort(inventory, new Comparator<Apple>() { public int compare(Apple a1, Apple a2){ return a1.getWeight().compareTo(a2.getWeight()); } }); // 流 // Apple::getWeight作为参数传递给comparing()方法? // comparing(Apple::getWeight)作为参数传递给sort()方法? inventory.sort(comparing(Apple::getWeight));

2024-01-01by@794842744-UcEbn&@GPT-4.Model: gpt-4
794842744-UcEbn

Collections.sort(inventory, new Comparator<Apple>() {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}
});

// 流
// Apple::getWeight作为参数传递给comparing()方法?
// comparing(Apple::getWeight)作为参数传递给sort()方法?
inventory.sort(comparing(Apple::getWeight));

Avatar
Avatar

In the given code snippet, you have two different ways of sorting a list of Apple objects (inventory) based on their weight.

The first approach uses an anonymous inner class implementing the Comparator interface to define how the Apples should be compared:

Collections.sort(inventory, new Comparator<Apple>() { 
    public int compare(Apple a1, Apple a2){ 
        return a1.getWeight().compareTo(a2.getWeight()); 
    } 
});

This is the older style, pre-Java 8 way of sorting where you explicitly create a Comparator to compare Apple objects based on their weight.

The second approach uses Java 8's lambda expressions and method references:

inventory.sort(comparing(Apple::getWeight));

In this line, the comparing method is a static method of Comparator that takes a