Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.Ordering;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

public class Main {
    /**
     * Adds items to the array list and sorts it based on natural ordering.
     *
     * @param <T>
     * @param values
     * @return
     */
    public static <T extends Comparable<? super T>> ArrayList<T> newSortedArrayList(Iterable<T> values) {
        return newSortedArrayList(values, Ordering.<T>natural());
    }

    /**
     * Creates a new list and sorts it with the comparator provided.
     *
     * @param <T>
     * @param values
     * @param comparator
     * @return
     */
    public static <T> ArrayList<T> newSortedArrayList(Iterable<T> values, Comparator<T> comparator) {
        checkNotNull(values);
        checkNotNull(comparator);

        ArrayList<T> result = values instanceof Collection ? new ArrayList<T>(((Collection) values).size())
                : new ArrayList<T>();

        for (T value : values) {
            result.add(value);
        }

        Collections.sort(result, comparator);

        return result;
    }
}