Java Data Structure How to - Determines if the array list is sorted








Question

We would like to know how to determines if the array list is sorted.

Answer

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*from  w  w w. ja  va2s  . c  o  m*/
public class Main {
  public static void main(String[] args) {
    List<String> l1 = new ArrayList<String>();
    List<String> l2 = new ArrayList<String>();
    l1.add("a");
    l1.add("b");
    l1.add("c");

    l2.add("b");
    l2.add("c");
    l2.add("a");

    if (isSorted(l1)) {
      System.out.println("already sorted");
    } else {
      Collections.sort(l1);
    }
  }

  public static boolean isSorted(List<String> list) {
    String previous = "";
    for (String current : list) {
      if (current.compareTo(previous) < 0)
        return false;
      previous = current;
    }
    return true;
  }
}

The code above generates the following result.