在Java-8中,有没有一种更好的方法来对集合进行排序,而不首先检查集合是空的还是空的?
if (institutions != null && !institutions.isEmpty()) {
Collections.sort(institutions);
}发布于 2020-02-14 03:28:13
虽然这个问题很老,但只需添加另一种方法即可。首先,集合不应该为空。如果是这样的话:
institutions.sort(Comparator.comparing(Institutions::getId));发布于 2016-08-22 21:03:21
我只能想到3 (4)种方法:
然后是普通的Collections.sort()。您不必检查您的列表是否为空,但是您必须确保它不为空。不过,坦率地说,您是否有过这样的用例:您的列表为空,并且您希望对其进行排序?这听起来可能是一个设计问题。
最后,您可以使用streams返回已排序的流。我写了一个小测试来测量这个过程的时间:
public static void main(String[] args) {
List<Integer> t1 = new ArrayList<>();
List<Integer> t2 = new ArrayList<>();
List<Integer> t3 = new ArrayList<>();
for(int i = 0; i< 100_000_00; i++) {
int tmp = new Random().nextInt();
t1.add(tmp);
t2.add(tmp);
t3.add(tmp);
}
long start = System.currentTimeMillis();
t1.sort(null); // equivalent to Collections.sort() - in place sort
System.out.println("T1 Took: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
List<Integer> sortedT2 = t2.stream().sorted().collect(Collectors.toList());
System.out.println("T2 Took: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
List<Integer> sortedT3 = t3.parallelStream().sorted().collect(Collectors.toList());
System.out.println("T3 Took: " + (System.currentTimeMillis() - start));
}对随机整数进行排序的结果是:(显然是在我的盒子上)
Collections.sort() -> 4163
stream.sorted() -> 4485
parallelStream().sorted() -> 1620以下是几点:
Collections.sort()和List#sort将对现有列表进行排序。流API (并行和普通)将创建新的排序列表。
再说一次-流可以是空的,但不能是null。看起来并行流是最快的,但是你必须记住并行流的陷阱。阅读一些信息,例如:Should I always use a parallel stream when possible?
最后,如果您想在之前检查null,您可以编写自己的静态帮助器,例如:
public static <T extends Comparable<? super T>> void saveSort(final List<T> myList) {
if(myList != null) {
myList.sort(null);
}
}
public static <T> void saveSort(final List<T> myList, Comparator<T> comparator) {
if(myList != null) {
myList.sort(comparator);
}
}我希望这对你有帮助!
编辑:排序的另一个Java8优势是以lambda的形式提供比较器:
List<Integer> test = Arrays.asList(4,2,1,3);
test.sort((i1, i2) -> i1.compareTo(i2));
test.forEach(System.out::println);https://stackoverflow.com/questions/39079270
复制相似问题