Java List Sort sortedInsert(List list, E e, Comparator c)

Here you can find the source of sortedInsert(List list, E e, Comparator c)

Description

Inserts an element into a sorted list

License

Open Source License

Parameter

Parameter Description
list a parameter
e a parameter
c a parameter

Declaration

@SuppressWarnings("unchecked")
public static <E> void sortedInsert(List<? extends E> list, E e, Comparator<? super E> c) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class Main {
    /**// w w w .  j  a v  a2s .  c  o m
     * Inserts an element into a sorted list
     * @param list
     * @param e
     * @param c
     */
    @SuppressWarnings("unchecked")
    public static <E> void sortedInsert(List<? extends E> list, E e, Comparator<? super E> c) {

        // We assume the list is sorted
        assert isSorted(list, c);

        int index = Collections.binarySearch(list, e, c);

        if (index >= 0)
            ((List<E>) list).add(index, e);
        else
            ((List<E>) list).add(-index - 1, e);

        assert isSorted(list, c) : list;
    }

    /**
     * Checks that the list is sorted
     * @param list
     * @param c
     * @return
     */
    public static <E> boolean isSorted(List<E> list, Comparator<? super E> c) {
        if (list.isEmpty())
            return true;

        Iterator<E> i = list.iterator();

        E lastR = i.next();

        while (i.hasNext()) {
            E r = i.next();

            if (c.compare(lastR, r) > 0)
                return false;
        }

        return true;
    }
}

Related

  1. sortByOccurencies(List lsSame)
  2. sorted(List l, Comparator comparator)
  3. sorted(List l, Comparator comparator)
  4. sorted(List l)
  5. sortedArray(List list)
  6. sortedInsert(List list, T item, Comparator comparator)
  7. sortedList(List list)
  8. sortedUnion(List args1, List args2)
  9. sortEntrySetToList(Set> set)

  10. HOME | Copyright © www.java2s.com 2016