Java Iterable Sort sort(Iterable things, Comparator comparator)

Here you can find the source of sort(Iterable things, Comparator comparator)

Description

Returns a sorted copy of the provided collection of things.

License

Apache License

Declaration

public static <T> List<T> sort(Iterable<? extends T> things, Comparator<? super T> comparator) 

Method Source Code

//package com.java2s;
/*/*from  ww w  . j  a va 2 s  .  c o m*/
 * Copyright 2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.*;

public class Main {
    /**
     * Returns a sorted copy of the provided collection of things. Uses the provided comparator to sort.
     */
    public static <T> List<T> sort(Iterable<? extends T> things, Comparator<? super T> comparator) {
        List<T> copy = toMutableList(things);
        Collections.sort(copy, comparator);
        return copy;
    }

    /**
     * Returns a sorted copy of the provided collection of things. Uses the natural ordering of the things.
     */
    public static <T extends Comparable> List<T> sort(Iterable<T> things) {
        List<T> copy = toMutableList(things);
        Collections.sort(copy);
        return copy;
    }

    private static <T> List<T> toMutableList(Iterable<? extends T> things) {
        if (things == null) {
            return new ArrayList<T>(0);
        }
        List<T> list = new ArrayList<T>();
        for (T thing : things) {
            list.add(thing);
        }
        return list;
    }
}

Related

  1. isSorted(Iterable iterable)
  2. isSorted(Iterable iterable, final Comparator cmp)
  3. sortAscending(Iterable elements)
  4. sorted(Iterable items)