我有一個簡單的問題。我有以下課程:
public class PostCollection {
private String name;
private List<Post> posts;
public PostCollection(String name, List<Post> posts) {
this.name = name;
this.posts = posts;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
}
然后我有一個List<PostCollection>我想對串列大小進行反向排序,所以最大的大小在前。要按從小到大的串列大小排序,我有這條線:
allCollections = allCollections.stream().sorted(Comparator.comparing(c -> c.getPosts().size())).collect(Collectors.toList());
所以我認為反向排序是:
allCollections = allCollections.stream().sorted(Comparator.comparing(c -> c.getPosts().size()).reversed()).collect(Collectors.toList());
但這給了我錯誤:
Cannot resolve method 'getPosts' in 'Object'
在方法上getPosts()....
我究竟做錯了什么?
uj5u.com熱心網友回復:
明確說明Comparator的型別可以解決問題:
allCollections =
allCollections.stream()
.sorted(Comparator.comparing((PostCollection c) -> c.getPosts().size())
.reversed())
.collect(Collectors.toList());
uj5u.com熱心網友回復:
以下將起作用。注意方法的<PostCollection, Integer>型別規范comparing(..)。
allCollections = allCollections.stream().sorted( Comparator.<PostCollection, Integer>comparing( c -> c.getPosts().size() ).reversed() ).collect( Collectors.toList() );
如果不指定實參,困難在于Comparator.comparing(..)取一個有super邊界限制的函式。由于您傳遞的是 lambda 而不是實作類,這意味著它可以回傳層次結構中從Comparator<Object>to 的任何內容Comparator<PostCollection>。所以,在這一點上,實際型別無法固定。
但是,如果您查看 的代碼Comparator.reversed(),它會呼叫Collections.reverseOrder(Comparator<S>),這意味著在呼叫它時,回傳的S中 的實際型別應該已經確定。正如我們所見,這是不可能的。ComparatorComparator.comparing(..)
因此,需要指定預期/預期的實際型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/373425.html
