Here you can find the source of compareByList(List
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 |
public static <T> int compareByList(List<T> list, T a, T b)
//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); } } }