Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate if an Array of strings is sorted in alphabetical order or not using java?

How to validate the String is in alphabetical order or not? It is just to validate that String is in order or not?

Can anybody help me how to validate? Here is my code::

public class Example3 {

    public static void main(String[] args) {

        String Month[]={"Jan", "Add", "Siri", "Xenon", "Cat"};

        for(int i=0; i<Month.length; i++) {     
            System.out.println(Month[i]);                   
        }
    }
}
like image 653
Chanakya Avatar asked Dec 22 '25 13:12

Chanakya


1 Answers

You could get the i-th (i >= 1) element and apply compareTo(String other) against the previous one:

boolean ordered = true;
for (int i = 1; i < month.length; i++) {
    if (month[i].compareTo(month[i - 1]) < 0) {
         ordered = false;
         break;
    }
}

System.out.println(ordered ? "Ordered" : "Unordered");
like image 78
Konstantin Yovkov Avatar answered Dec 24 '25 03:12

Konstantin Yovkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!