Example usage for java.util Comparator compare

List of usage examples for java.util Comparator compare

Introduction

In this page you can find the example usage for java.util Comparator compare.

Prototype

int compare(T o1, T o2);

Source Link

Document

Compares its two arguments for order.

Usage

From source file:Main.java

/**
 * Finds the last index where the value is located or
 * the index where it could be inserted, similar to the regular
 * binarySearch() methods, but it works with duplicate elements.
 * @param <T> the element type// w w  w.jav  a 2  s.c om
 * @param list the list to search
 * @param fromIndex the starting index, inclusive
 * @param toIndex the end index, exclusive
 * @param value the value to search
 * @param comparator the comparator
 * @return if positive, the exact index where the value is first
 * encountered, or -(insertion point - 1) if not in the array.
 */
public static <T> int findLastIterator(List<? extends T> list, int fromIndex, int toIndex, T value,
        Comparator<? super T> comparator) {
    int a = fromIndex;
    int b = toIndex;
    ListIterator<? extends T> it = list.listIterator();
    while (a <= b) {
        int mid = a + (b - a) / 2;
        T midVal = get(it, mid);
        int c = comparator.compare(midVal, value);
        if (c < 0) {
            a = mid + 1;
        } else if (c > 0) {
            b = mid - 1;
        } else {
            if (mid < toIndex - 1) {
                if (comparator.compare(get(it, mid + 1), value) != 0) {
                    return mid;
                } else {
                    a = mid + 1;
                }
            } else {
                return 0;
            }
        }
    }
    return -(a + 1);
}

From source file:Main.java

public static <K, V> Comparator<Entry<K, V>> entryComparator(final Comparator<? super K> keyComparator) {
    return new Comparator<Entry<K, V>>() {
        @Override/*from www  .  j  a v a 2 s .  c  om*/
        @SuppressWarnings("unchecked")
        // no less safe than putting it in the map!
        public int compare(Entry<K, V> a, Entry<K, V> b) {
            return (keyComparator == null) ? ((Comparable) a.getKey()).compareTo(b.getKey())
                    : keyComparator.compare(a.getKey(), b.getKey());
        }
    };
}

From source file:Main.java

public static <T> Integer[] getSortedArrayIndexes(final T[] array, final Comparator<T> comparator) {
    Integer[] indexes = new Integer[array.length];
    for (int i = 0; i < indexes.length; i++) {
        indexes[i] = i;//  ww  w. j  a  va 2s.c o m
    }

    if (comparator != null) {
        Arrays.sort(indexes, new Comparator<Integer>() {
            @Override
            public int compare(Integer aIndex, Integer bIndex) {
                return comparator.compare(array[aIndex], array[bIndex]);
            }
        });
    }

    return indexes;
}

From source file:Main.java

public static <T> int compareAsIterable(Comparator<? super T> comparator, Iterable<? extends T> it1,
        Iterable<? extends T> it2) {
    Iterator<? extends T> elements2 = it2.iterator();
    for (T element1 : it1) {
        T element2;//w w w .j  a v  a 2s  .co m
        try {
            element2 = elements2.next();
        } catch (NoSuchElementException ex) {
            return 1;
        }
        int res = comparator.compare(element1, element2);
        if (res != 0)
            return res;
    }
    if (elements2.hasNext()) {
        return -1;
    }
    return 0;
}

From source file:Main.java

/**
 * Sorts a collection using a comparator and returns it as a {@link List}
 *
 * @param c       Collection to be sorted
 * @param k       Comparator to sort by/*w  w w .ja  v a 2 s  .co m*/
 * @param reverse Whether to reverse the sort order
 * @return a {@link List} of the sorted elements
 * @throws IllegalAccessException when unable to access the comparator class
 * @throws InstantiationException when unable to instantiate to comparator class
 */
public static <E> List<E> sortByCompare(Collection<E> c, Class<? extends Comparator<E>> k, boolean reverse)
        throws IllegalAccessException, InstantiationException {
    Comparator<E> comp = k.newInstance();
    int moves = 0;
    boolean firstRun = true;
    LinkedList<E> l = new LinkedList<>(c);

    while (moves > 0 || firstRun) {
        firstRun = false;
        moves = 0;

        for (int i = 1; i < l.size(); i++) {
            E a = l.get(i - 1);
            E b = l.get(i);
            if (reverse ? comp.compare(a, b) < 0 : comp.compare(a, b) > 0) {
                l.set(i - 1, b);
                l.set(i, a);
                moves++;
            }
        }
    }
    return l;
}

From source file:Main.java

public static <T> int compareAsIterable(@Nonnull Comparator<? super T> comparator,
        @Nonnull Iterable<? extends T> it1, @Nonnull Iterable<? extends T> it2) {
    Iterator<? extends T> elements2 = it2.iterator();
    for (T element1 : it1) {
        T element2;// www  .ja  v  a  2 s .  c  o  m
        try {
            element2 = elements2.next();
        } catch (NoSuchElementException ex) {
            return 1;
        }
        int res = comparator.compare(element1, element2);
        if (res != 0)
            return res;
    }
    if (elements2.hasNext()) {
        return -1;
    }
    return 0;
}

From source file:afest.math.MyMath.java

/**
 * Return the maximum element a such that for all b in the collection a > b according to the comparator.
 * @param <T> Type of elements present in the list.
 * @param collection collection of elements to get the largest from.
 * @param comparator comparator used to order the elements in the collection.
 * @return the maximum element a such that for all b in the collection a > b according to the comparator.
 *//*from w  ww.  j  a v a2s.c om*/
public static <T> T max(Collection<T> collection, Comparator<T> comparator) {
    T max = null;
    for (T element : collection) {
        if (max == null) {
            max = element;
        }
        if (comparator.compare(max, element) < 0) {
            max = element;
        }
    }
    return max;
}

From source file:Main.java

public static <T> void quicksort(T[] array, int left0, int right0, Comparator<? super T> c) {

    int left, right;
    T pivot, temp;/*from   w w w  .ja va 2s  .co m*/
    left = left0;
    right = right0 + 1;

    final int pivotIndex = (left0 + right0) / 2;
    pivot = array[pivotIndex];
    temp = array[left0];
    array[left0] = pivot;
    array[pivotIndex] = temp;

    do {

        do
            left++;
        while (left <= right0 && c.compare(array[left], pivot) < 0);

        do
            right--;
        while (c.compare(array[right], pivot) > 0);

        if (left < right) {
            temp = array[left];
            array[left] = array[right];
            array[right] = temp;
        }

    } while (left <= right);

    temp = array[left0];
    array[left0] = array[right];
    array[right] = temp;

    if (left0 < right)
        quicksort(array, left0, right, c);
    if (left < right0)
        quicksort(array, left, right0, c);

}

From source file:Main.java

/**
 * Compare two lists using the {@code comparator} for all comparisons (not using the equals() operator)
 * @param lhs Left hand side//  w w  w.  j  a  va  2s . co m
 * @param rhs Right hand side
 * @param comparator Comparator which will be used for all comparisons (equals() on objects will not be used)
 * @return True if {@code lhs} == {@code rhs} according to {@code comparator}. False otherwise.
 */
public static <T> boolean equals(List<T> lhs, List<T> rhs, Comparator<? super T> comparator) {
    final int lhsSize = lhs.size();
    if (lhsSize != rhs.size()) {
        return false;
    }

    // Don't use a TreeSet to do the comparison.  We want to force the comparator
    // to be used instead of the object's equals()
    Collections.sort(lhs, comparator);
    Collections.sort(rhs, comparator);
    for (int i = 0; i < lhsSize; ++i) {
        if (comparator.compare(lhs.get(i), rhs.get(i)) != 0) {
            return false;
        }
    }
    return true;
}

From source file:Main.java

/**
 * Merge two ascending/descending array and keep the first n elements.
 * @param ascending// w  ww. j  av  a 2s . co m
 *            if true, the array is sorted in ascending order,
 *            otherwise it is in descending order.
 */
static <T extends Comparable<T>> ArrayList<T> sortedMerge(List<T> a1, List<T> a2, boolean ascending, int n) {

    Comparator<T> comparator = getComparator(ascending, (T) null);

    int n1 = a1.size();
    int n2 = a2.size();
    int p1 = 0; // The current element in a1
    int p2 = 0; // The current element in a2

    ArrayList<T> output = new ArrayList<T>(n);

    while (output.size() < n && (p1 < n1 || p2 < n2)) {
        if (p1 < n1) {
            if (p2 == n2 || comparator.compare(a1.get(p1), a2.get(p2)) < 0) {
                output.add(a1.get(p1++));
            }
        }
        if (output.size() == n) {
            break;
        }
        if (p2 < n2) {
            if (p1 == n1 || comparator.compare(a2.get(p2), a1.get(p1)) < 0) {
                output.add(a2.get(p2++));
            }
        }
    }

    return output;
}