comparator Java 8新的静态方法comparing

compareTo &&comparing

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

public class ComparingDemo {

    public static void main(String[] args) {

        List tracks= Arrays.asList(new Track("Bakai",5234),new Track("Violets for your fur",365),
                new Track("Time was",453));
        Track shortestTack=tracks.stream().min(Comparator.comparing(Track::getName)).get();
        Track shortestTack1= tracks.stream().min(Comparator.comparing(track -> track.getName())).get();
        System.out.println(shortestTack1);
//        tracks.sort(Comparator.comparing(Track::getName));
    }
}

streammax方法返回Optional对象,Optional对象代表可能存在也可能不存在的值。如果stream为空,该值不存在,如果不为空该值存在,通过调用get方法可以取出Optional对象的值。

你可能感兴趣的:(comparator Java 8新的静态方法comparing)