The LinkedHashMap
class has already been mentioned a few times, however, this class is designed to maintain insertion order. But one can also use TreeMap
, which is designed to keep an arbitrary ordering by some Comparator
(or the natural ordering if the no-args constructor is used).
I have written some helper method to convert a given list to a Comparator
which uses the order provided by the list:
public static <T> Comparator<T> ofOrder(List<T> elements) {
Map<T, Integer> comparatorMap = IntStream.range(0, elements.size())
.collect(HashMap::new, (map, value) -> map.put(elements.get(value), value), HashMap::putAll);
return (T left, T right) -> {
int leftVal = comparatorMap.getOrDefault(left, Integer.MAX_VALUE);
int rightVal = comparatorMap.getOrDefault(right, Integer.MAX_VALUE);
return Integer.compare(leftVal, rightVal);
};
}
With this method it's fairly easy to get a TreeMap
with the desired ordering:
TreeMap<String, String> treeMap = new TreeMap<>(ofOrder(list));
treeMap.putAll(map);