Java List Sort ListToSortedArray(List list)

Here you can find the source of ListToSortedArray(List list)

Description

Convert a List of Integer s to a sorted array of ints.

License

Apache License

Parameter

Parameter Description
list The List to convert.

Return

an int[] or null if list is null.

Declaration

public static int[] ListToSortedArray(List<Integer> list) 

Method Source Code


//package com.java2s;
/*/* w w w  .ja  v  a  2 s  .c o m*/
 * Copyright (C) 2013 Marten Gajda <marten@dmfs.org>
 *
 * 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.Arrays;
import java.util.List;

public class Main {
    /**
     * Convert a {@link List} of {@link Integer}s to a sorted array of <code>int</code>s.
     * 
     * @param list
     *            The {@link List} to convert.
     * @return an int[] or <code>null</code> if <code>list</code> is <code>null</code>.
     */
    public static int[] ListToSortedArray(List<Integer> list) {
        if (list == null) {
            return null;
        }

        int count = list.size();
        int[] result = new int[count];
        int last = Integer.MIN_VALUE;
        boolean needsSorting = false;

        for (int i = 0; i < count; ++i) {
            int element = result[i] = list.get(i);
            needsSorting |= last > element;
            last = element;
        }
        if (needsSorting) {
            Arrays.sort(result);
        }
        return result;
    }
}

Related

  1. isSorted(List list)
  2. isSorted(List list)
  3. isSortedDescending(List list)
  4. isStringListSortedDesc(List list)
  5. isUnsortedEventsMatch(List actual, List expected)
  6. mapTosortedScoreList(HashMap unSortedMap)
  7. maximum(List sortedDataAscendingOrder)
  8. mergeLong(List l1, List l2, boolean sort)
  9. mergeSort(List m)