Sorting a List in parallel without creating a temporary array in Java 8

后端 未结 5 817
小鲜肉
小鲜肉 2020-12-03 13:13

Java 8 provides java.util.Arrays.parallelSort, which sorts arrays in parallel using the fork-join framework. But there\'s no corresponding Collections.parallelSort

5条回答
  •  渐次进展
    2020-12-03 13:44

    By combining the existing answers I came up with this code.
    This works if you are not interested in creating a custom List class and if you don't bother to create a temporary array (Collections.sort is doing it anyway).
    This uses the initial list and does not create a new one as in the parallelStream solution.

    // Convert List to Array so we can use Arrays.parallelSort rather than Collections.sort.
    // Note that Collections.sort begins with this very same conversion, so we're not adding overhead
    // in comparaison with Collections.sort.
    Foo[] fooArr = fooLst.toArray(new Foo[0]);
    
    // Multithread the TimSort. Automatically fallback to mono-thread when size is less than 8192.
    Arrays.parallelSort(fooArr, Comparator.comparingStuff(Foo::yourmethod));
    
    // Refill the List using the sorted Array, the same way Collections.sort does it.
    ListIterator i = fooLst.listIterator();
    for (Foo e : fooArr) {
        i.next();
        i.set((Foo) e);
    }
    

提交回复
热议问题