Java Iterable Sort sorted(Iterable items)

Here you can find the source of sorted(Iterable items)

Description

Return the items of an Iterable as a sorted list.

License

Open Source License

Parameter

Parameter Description
T The type of items in the Iterable.
items The collection to be sorted.

Return

A list containing the same items as the Iterable, but sorted.

Declaration

public static <T extends Comparable<T>> List<T> sorted(Iterable<T> items) 

Method Source Code

//package com.java2s;

import java.util.*;

public class Main {
    /**/*from  w ww .  ja  va 2 s  .c om*/
     * Return the items of an Iterable as a sorted list.
     *
     * @param <T> The type of items in the Iterable.
     * @param items The collection to be sorted.
     * @return A list containing the same items as the Iterable, but sorted.
     */
    public static <T extends Comparable<T>> List<T> sorted(Iterable<T> items) {
        List<T> result = toList(items);
        Collections.sort(result);
        return result;
    }

    /**
     * Return the items of an Iterable as a sorted list.
     *
     * @param <T> The type of items in the Iterable.
     * @param items The collection to be sorted.
     * @return A list containing the same items as the Iterable, but sorted.
     */
    public static <T> List<T> sorted(Iterable<T> items, Comparator<T> comparator) {
        List<T> result = toList(items);
        Collections.sort(result, comparator);
        return result;
    }

    /**
     * Create a list out of the items in the Iterable.
     *
     * @param <T> The type of items in the Iterable.
     * @param items The items to be made into a list.
     * @return A list consisting of the items of the Iterable, in the same order.
     */
    public static <T> List<T> toList(Iterable<T> items) {
        List<T> list = new ArrayList<>();
        addAll(list, items);
        return list;
    }

    /**
     * Add all the items from an iterable to a collection.
     *
     * @param <T> The type of items in the iterable and the collection
     * @param collection The collection to which the items should be added.
     * @param items The items to add to the collection.
     */
    public static <T> void addAll(Collection<T> collection, Iterable<? extends T> items) {
        for (T item : items) {
            collection.add(item);
        }
    }
}

Related

  1. isSorted(Iterable iterable)
  2. isSorted(Iterable iterable, final Comparator cmp)
  3. sort(Iterable things, Comparator comparator)
  4. sortAscending(Iterable elements)