Comparator.comparing 在 java 8 个流中没有方法引用时无法工作
Comparator.comparing not working without Method reference in java 8 streams
List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal::getName)).collect(Collectors.toList());
//working
同时
List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal.getName()).collect(Collectors.toList());
//Not working..
谁能告诉我为什么我不能在没有方法参考的情况下使用比较器进行比较?
除非getName()
是静态方法,否则它可能无法编译。
如果您不想使用方法引用(它不是语法糖),使用 lambda 也应该可行。
animals.stream().sorted(Comparator.comparing(a -> a.getName()).collect(Collectors.toList());
Accepts a function that extracts a Comparable sort key from a type T,
and returns a Comparator that compares by that sort key.
Animal::getName
给出方法参考,而 Animal.getName()
给你一个 String
(可能)。
参考:
:: (double colon) operator in Java 8
List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal::getName)).collect(Collectors.toList());
//working
同时
List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal.getName()).collect(Collectors.toList());
//Not working..
谁能告诉我为什么我不能在没有方法参考的情况下使用比较器进行比较?
除非getName()
是静态方法,否则它可能无法编译。
如果您不想使用方法引用(它不是语法糖),使用 lambda 也应该可行。
animals.stream().sorted(Comparator.comparing(a -> a.getName()).collect(Collectors.toList());
Accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator that compares by that sort key.
Animal::getName
给出方法参考,而 Animal.getName()
给你一个 String
(可能)。
参考:
:: (double colon) operator in Java 8