Java先按长度排序,然后按字母顺序排序



我已经可以按描述长度排序了,但是如果两个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);
}

}

在这种情况下如何使用比较器?或者我应该把它改成别的?

您的自定义比较器看起来不错。然而,在streamssorted方法中,您使用另一个比较器。

考虑到自定义比较器与下面的代码块位于同一个类中,这就是您可以如何插入自定义比较器的方法。

return articles.stream()
.sorted(this::compare)
.collect(Collectors.toList());

如果您需要先按描述长度然后按描述(字母顺序)排序,那么您的第一次比较是好的,但您还需要添加第二次比较按描述

您可以使用thenComparing()方法进行第二次比较。它将只对长度相同的元素执行第二次比较。在这种情况下,不需要实现自定义Comparator

public List<Article> sortAsc() {
removeNull();
return articles.stream()
.sorted(Comparator.comparingInt((Article a) -> a.getDescription().length())
.thenComparing(Article::getDescription))
.collect(Collectors.toList());
}

为什么你需要在stream中排序,你可以简单地为你的列表调用'sort'方法。

articles.sort(new ComparatorAppController()); 

可以在sort方法中添加n个比较器。如:-

articles.sort(new ComparatorAppController().thenComparing(new SomeOtherComparing())); 

您也可以在stream中使用thenComparing

articles.stream()
.sorted(Comparator.comparingInt(a -> a.getDescription().length()).thenComparing(new SomeOtherComparing()))
.collect(Collectors.toList());

使用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());
}

删除比较器并使用comparing()thenComparing()构建一个:

articles.stream()
.sorted(Comparator.comparing(a -> a.getDescription().length())
.thenComparing(Article::getDescription))
.collect(Collectors.toList());

最新更新