I am looking for a way to find out in run-time, whether a collection is ordered or not. Any way to do this?
EDIT: I am sorry for wrongly asked question. I meant whether there is some general way to say HashMap does not store order of elements being inserted, where LinkedHashMap does.
For elements that implement the Comparable
interface, you can check to see if they are in their "natural" order.
public static <T extends Comparable<? super T>> boolean isOrdered(Iterable<T> list) {
Iterator<T> i = list.iterator();
if (i.hasNext()) {
T previous = i.next();
while (i.hasNext()) {
T current = i.next();
if (previous.compareTo(current) > 0)
return false;
previous = current;
}
}
return true;
}
Otherwise, you'll have to define a Comparator
that can compare your objects according to your definition of order, and pass that to the test.
public static <T> boolean isOrdered(Iterable<T> list, Comparator<? super T> c) {
Iterator<T> i = list.iterator();
if (i.hasNext()) {
T previous = i.next();
while (i.hasNext()) {
T current = i.next();
if (c.compare(previous, current) > 0)
return false;
previous = current;
}
}
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With