[英]Easiest sortig of list of objects with java 8 lambda
我有一個包含對象的列表,我正在尋找最簡單的方法來用Java 8對該列表進行排序:
public class MyClass {
private Integer someInteger;
private String someString;
}
private List<MyClass> myClasses;
在這個問題中,我已經嘗試了Java 8答案:
Collections.sort(myClasses, (MyClass m1, MyClass m2) -> m1.someInteger.compareTo(m2.someInteger));
但是我的Eclipse大喊:
The method sort(List<T>, Comparator<? super T>) in the type
Collections is not applicable for the arguments (List<MyClass>,
(MyClass m1, MyClass m2) -> {})
和:
Type mismatch: cannot convert from Comparator<MyClass> to Comparator<? super T>
我還找到了另一個示例:
myClasses.sort(Comparator.comparing(MyClasse::getSomeInteger));
但也有錯誤:
The method sort(Comparator<? super MyClass>) in the type List<MyClass>
is not applicable for the arguments (Comparator<MyClass>)
那么我怎么能以最簡單的方式做呢?
編譯器錯誤在這里有點誤導。 在這種情況下,它只是告訴您lambda表達式不會編譯。 具體來說,由於您嘗試從MyClass
外部訪問私有字段的原因。
例如以下行:
Collections.sort(myClasses, (MyClass m1, MyClass m2) -> m1.nonExistingField);
會產生相同的錯誤:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (List<MyClass>, (MyClass m1, MyClass m2) -> {})
Comparator<MyClass> cannot be resolved to a type
MyClass cannot be resolved to a type
MyClass cannot be resolved to a type
at ap.MyClass.main(MyClass.java:11)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.