使用 Java Stream 實現集合排序


排序集合中的對象

1.源碼介紹

1.1 Stream sorted()

源碼查看:

/**
 * Returns a stream consisting of the elements of this stream, sorted
 * according to natural order.  If the elements of this stream are not
 * {@code Comparable}, a {@code java.lang.ClassCastException} may be thrown
 * when the terminal operation is executed.
 *
 * <p>For ordered streams, the sort is stable.  For unordered streams, no
 * stability guarantees are made.
 *
 * <p>This is a <a href="package-summary.html#StreamOps">stateful
 * intermediate operation</a>.
 *
 * @return the new stream
 */
Stream<T> sorted();

說明:T 必須是實現了 Comparable 接口的類,否則方法會拋出 ClassCastException 異常。

1.2. Stream sorted(Comparator<? super T> comparator)

源碼查看:

/**
 * Returns a stream consisting of the elements of this stream, sorted
 * according to the provided {@code Comparator}.
 *
 * <p>For ordered streams, the sort is stable.  For unordered streams, no
 * stability guarantees are made.
 *
 * <p>This is a <a href="package-summary.html#StreamOps">stateful
 * intermediate operation</a>.
 *
 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>,
 *                   <a href="package-summary.html#Statelessness">stateless</a>
 *                   {@code Comparator} to be used to compare stream elements
 * @return the new stream
 */
Stream<T> sorted(Comparator<? super T> comparator);

說明:根據給定的 比較器 進行排序。Comparator是一個函數式接口,其源碼如下(僅展示關鍵部分):

@FunctionalInterface
public interface Comparator<T> {
    /**
     * Compares its two arguments for order.  Returns a negative integer,
     * zero, or a positive integer as the first argument is less than, equal
     * to, or greater than the second.<p>
     * 
     * ......(此處略去部分注釋)
     *
     * @param o1 the first object to be compared.
     * @param o2 the second object to be compared.
     * @return a negative integer, zero, or a positive integer as the
     *         first argument is less than, equal to, or greater than the
     *         second.
     * @throws NullPointerException if an argument is null and this
     *         comparator does not permit null arguments
     * @throws ClassCastException if the arguments' types prevent them from
     *         being compared by this comparator.
     */
    int compare(T o1, T o2);

說明:方法的返回值分類以及含義如下:

  • 負數:o1 小於 o2
  • 0:o1 等於 o2
  • 正數:o1 大於 o2

3. 使用

3.1 Stream sorted()

3.2 Stream sorted(Comparator<? super T> comparator)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM