来自静态方法的实例方法的方法引用

method reference for instance method from static method

对不起,标题不清楚,我对这个甚至英语还是个新手。

Collections.sort(aList, (s1, s2) -> Float.compare(s1.getAFloat(), s2.getAFloat()));

如上,我可以使用方法引用吗?如果 s1s2Float 并且他们不使用 get-a-float 方法那么事情就变得容易了:

Collections.sort(aList,Float::compare);

但是s1.getAFloat()我不知道如何使用方法参考,甚至不知道如何使用它,谢谢您的回答!

不,你不能。查看以下代码。

List<Float> aList = Arrays.asList(5.2f, 9.7f);
Collections.sort(aList, (s1, s2) -> Float.compare(s1, s2));
Collections.sort(aList, Float::compare);

如果您的列表元素直接属于 Float 类型,那么您将使用 method-reference.

如果元素不是 Float 类型那么你可以这样做。

List<String> aList2 = Arrays.asList("5.2f", "9.7f");  
aList2.stream().map(Float::valueOf).sorted(Float::compare)
                 .collect(Collectors.toList());

您可以使用

Collections.sort(aList, Comparator.comparing(ItemType::getAFloat));

如果检索到的类型已经不可排序,您可以为 comparing 提供一个额外的比较器。