Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Checking if an ArrayList of String are in alphabetical order

I have an ArrayList called account which contains Strings. I'm trying to write a method that checks if they are in order and returns true or false based on whether they are in order or not.

How would you go about this? I've already tried checking the initial chracter with a for-loop but it went terribly wrong. I created a new ArrayList and set it equal to the original, then sorted it and compared them but since they contained the same data it always came back true.

Just an extra quick question, since I'm doing this for Strings, how would you check if some numbers were in ascending/descending order? Throught the same principal?

Thankyou!

like image 520
mino Avatar asked Jan 01 '12 21:01

mino


1 Answers

Try this (assuming you want to compare the strings using their natural ordering, of course):

String previous = ""; // empty string: guaranteed to be less than or equal to any other

for (final String current: thelist) {
    if (current.compareTo(previous) < 0)
        return false;
    previous = current;
}

return true;

This is due to the fact that String implements Comparable<String>, and the comparison will be done using the strings' natural ordering.

like image 71
fge Avatar answered Oct 14 '22 12:10

fge