我已經可以按描述長度排序,但是Article
如果其中兩個具有相同的長度,我如何按字母順序對兩個進行排序?(如果兩篇文章的描述長度相同,則按字母排序)。
public List<Article> sortAsc() {
removeNull();
return articles.stream()
.sorted(Comparator.comparingInt(a -> a.getDescription().length()))
.collect(Collectors.toList());
}
public class ComparatorAppController implements Comparator<String> {
/***
* compare each element
* @param o1
* @param o2
* @return
*/
public int compare(String o1, String o2) {
// check length in one direction
if (o1.length() > o2.length()) {
return 1;
}
// check length in the other direction
else if (o1.length() < o2.length()) {
return -1;
}
// if same alphabetical order
return o1.compareTo(o2);
}
}
在這種情況下如何使用我的比較器?還是我應該將其更改為其他內容?
uj5u.com熱心網友回復:
您的自定義比較器似乎不錯。但是,在您使用另一個比較器的sorted
方法中。streams
考慮到它與以下代碼塊在同一個類中,這就是插入自定義比較器的方法。
return articles.stream()
.sorted(this::compare)
.collect(Collectors.toList());
uj5u.com熱心網友回復:
如果您需要先按描述長度然后按描述(字母順序)排序,那么您的第一個比較很好,但您還需要按描述添加第二個比較。
您可以使用 方法堆疊第二個比較thenComparing()
。它將僅對具有相同長度的元素執行第二次比較。無需Comparator
為此場景實作自定義。
public List<Article> sortAsc() {
removeNull();
return articles.stream()
.sorted(Comparator.comparingInt((Article a) -> a.getDescription().length())
.thenComparing(Article::getDescription))
.collect(Collectors.toList());
}
uj5u.com熱心網友回復:
為什么你需要排序stream
,你可以簡單地為你的串列呼叫“排序”方法。
articles.sort(new ComparatorAppController());
您可以在方法中添加 n 個比較器sort
。例如:-
articles.sort(new ComparatorAppController().thenComparing(new SomeOtherComparing()));
也可以用thenComparing
在stream
也??。
articles.stream()
.sorted(Comparator.comparingInt(a -> a.getDescription().length()).thenComparing(new SomeOtherComparing()))
.collect(Collectors.toList());
uj5u.com熱心網友回復:
利用Comparator.comparing(KeyExtractor,Comparator)
public List<Article> sortAsc() {
removeNull();
return articles.stream()
.sorted(Comparator.comparing(a -> a.getDescription(), new ComparatorAppController()))
.collect(Collectors.toList());
}
或者用一些定義所有的標準thenComparing*
public static List<Article> sortAsc() {
return articles.stream()
.sorted(Comparator.<Article>comparingInt(a -> a.getDescription().length())
.thenComparing(Article::getDescription))
.collect(Collectors.toList());
}
uj5u.com熱心網友回復:
comparing()
洗掉您的比較器并使用and構建一個thenComparing()
:
articles.stream()
.sorted(Comparator.comparing(a -> a.getDescription().length())
.thenComparing(Article::getDescription))
.collect(Collectors.toList());
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/482218.html
上一篇:根據值和索引對熊貓系列進行排序
下一篇:回傳Java年齡第二年輕的串列