Java List Compare compareByList(List list, T a, T b)

Here you can find the source of compareByList(List list, T a, T b)

Description

Compare two items, with the ordering determined by a list of those items.

License

Apache License

Parameter

Parameter Description
T the list type
list the list, not null
a the first object, may be null
b the second object, may be null

Return

0, if equal, -1 if a < b, +1 if a > b

Declaration

public static <T> int compareByList(List<T> list, T a, T b) 

Method Source Code


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

import java.util.List;

public class Main {
    /**/*from  ww w. j  a v  a2s.c o m*/
     * Compare two items, with the ordering determined by a list of those items.
     * <p>
     * Nulls are permitted and sort low, and if a or b are not in the list, then
     * the result of comparing the toString() output is used instead.
     * 
     * @param <T> the list type
     * @param list  the list, not null
     * @param a  the first object, may be null
     * @param b  the second object, may be null
     * @return 0, if equal, -1 if a < b, +1 if a > b
     */
    public static <T> int compareByList(List<T> list, T a, T b) {
        if (a == null) {
            if (b == null) {
                return 0;
            } else {
                return -1;
            }
        } else {
            if (b == null) {
                return 1;
            } else {
                if (list.contains(a) && list.contains(b)) {
                    return list.indexOf(a) - list.indexOf(b);
                } else {
                    return compareWithNullLow(a.toString(), b.toString());
                }
            }
        }
    }

    /**
     * Compares two objects, either of which might be null, sorting nulls low.
     * 
     * @param <E>  the type of object being compared
     * @param a  item that compareTo is called on
     * @param b  item that is being compared
     * @return negative when a less than b, zero when equal, positive when greater
     */
    public static <E> int compareWithNullLow(Comparable<E> a, E b) {
        if (a == null) {
            return b == null ? 0 : -1;
        } else if (b == null) {
            return 1; // a not null
        } else {
            return a.compareTo(b);
        }
    }
}

Related

  1. compare(List list1, List list2)
  2. compare(List a, List b)
  3. compare(List strList1, List strList2)
  4. compare(List a, List b)
  5. compare(String str, List list)
  6. compareFileLists(List expected, List gotten)
  7. compareIncarnations(List e1, List e2)
  8. compareList(List listA, List listB)
  9. compareList(Object eObj, Object rObj)