比较器复合

1. 逆序:

package com.ant.jdk8.chap03;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class ComparatorCompositeDemo {
    public static void main(String[] args) {
        List<Apple> apples = Arrays.asList(new Apple("green",2,"China"),
                new Apple("green",1,"Japan"),
                new Apple("red",3,"America"));
        apples.sort(Comparator.comparing(Apple::getWeight).reversed());
        apples.stream().forEach(apple-> System.out.println(apple.getWeight()));
    }
}

2. 比较器链:

package com.ant.jdk8.chap03;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class ComparatorCompositeDemo {
    public static void main(String[] args) {
        List<Apple> apples = Arrays.asList(new Apple("green",2,"China"),
                new Apple("green",2,"Japan"),
                new Apple("red",3,"America"));
        apples.sort(Comparator.comparing(Apple::getWeight).reversed().thenComparing(Apple::getCountry));
        apples.stream().forEach(apple-> System.out.println(apple.getWeight()+"->"+apple.getCountry()));
    }
}

猜你喜欢

转载自www.cnblogs.com/i-hard-working/p/9575660.html