Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - a way to find out whether collection is ordered or not

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.

like image 914
Jarek Avatar asked Feb 21 '23 18:02

Jarek


1 Answers

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;
}
like image 187
erickson Avatar answered Mar 06 '23 01:03

erickson