T
- the type of objects that may be compared by this comparatorpublic class PreferenceListComparator<T> extends Object implements Comparator<T>, MapSorter<T>
The items at the start of the preference list are placed before (that is deemed smaller than) the other items. The items that appear in the preference list are placed before the items that do not appear in the preference list. The order of items that do not appear in the preference list is not specified (and is application specific in practice). Thus the induced order is not guaranteed to be linear.
Usage example:
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
Map<K, V> unsorted;
List<K> preferenceList;
Comparator<K> comparator = new PreferenceListComparator<>(preferenceList);
SortedMap<K, V> sorted = new TreeMap<>(comparator);
sorted.putAll(unsorted);
Constructor and Description |
---|
PreferenceListComparator(Iterator<T> preferredIterator)
Creates a new comparator.
|
PreferenceListComparator(List<T> preferred)
Creates a new comparator.
|
PreferenceListComparator(T[] preferred)
Creates a new comparator.
|
Modifier and Type | Method and Description |
---|---|
int |
compare(T o1,
T o2)
Compares its two arguments for order.
|
static <K,V> SortedMap<K,V> |
sort(Map<K,V> unsorted,
Comparator<K> comparator)
Sorts a map by its keys using a comparator.
|
<V> SortedMap<T,V> |
sort(Map<T,V> unsorted)
Sorts a map by its keys.
|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
comparing, comparing, comparingDouble, comparingInt, comparingLong, equals, naturalOrder, nullsFirst, nullsLast, reversed, reverseOrder, thenComparing, thenComparing, thenComparing, thenComparingDouble, thenComparingInt, thenComparingLong
public PreferenceListComparator(List<T> preferred)
preferred
- the preference listpublic PreferenceListComparator(T[] preferred)
preferred
- the preference list specified by an arraypublic PreferenceListComparator(Iterator<T> preferredIterator)
preferredIterator
- an iterator that iterates over the items in the
order of preferencepublic int compare(T o1, T o2)
Note that this implementation violates some of the requirements imposed
by the Comparator
interface, so care should be taken when using
it. In practice, it at least allows a TreeMap
initialized by a
Comparator
to be used for one-time ordering of elements of a
Map
(using the method TreeMap.putAll(Map)
). Other uses of
the comparator have not been tested.
compare
in interface Comparator<T>
o1
- the first object to be compared.o2
- the second object to be compared.public static <K,V> SortedMap<K,V> sort(Map<K,V> unsorted, Comparator<K> comparator)
K
- the type of keysV
- the type of valuesunsorted
- the original (unsorted) mapcomparator
- a comparator on KCopyright © 2015–2016 Hobrasoft s.r.o.. All rights reserved.