【发布时间】:2017-08-03 15:05:27
【问题描述】:
我有以下sn-p:
List<O> os = new ArrayList<>();
os.add(new O("A", 3, "x"));
os.add(new O("A", 2, "y"));
os.add(new O("B", 1, "z"));
Comparator<O> byA = Comparator.comparing(O::getA);
Comparator<O> byB = Comparator.comparing(O::getB);
// I want to use rather this...
List<Comparator<O>> comparators = new ArrayList<>();
comparators.add(byA);
comparators.add(byB);
os.stream()
.sorted(byB.thenComparing(byA))
.forEach(o -> System.out.println(o.getC()));
如您所见,我明确使用两个比较器进行排序。但是,如果我在某个列表中有未知数量的比较器并且我想按它们全部排序怎么办?有什么办法吗?还是应该使用带有多个 if 的老式方式比较器?
【问题讨论】:
-
最好让
O实现Comparable,这样你就可以只使用Stream.sorted(),除非你使用不止一种排序方法(或者不能改变O类)。
标签: java sorting java-8 java-stream