How to check if all strings in array of strings are in ascending order with Java

2 Answers

0 votes
public class MyClass {
    static boolean isAscendingOrder(String[] strings) {
        String previous = strings[0];
        
        for (String string : strings) {
            if (string.compareTo(previous) < 0)
                return false;
            previous = string;
        }
        return true;
    }
    public static void main(String args[]) {
        String[] array = {"c", "c++", "java", "python"};
 
        System.out.println(isAscendingOrder(array));
    }
}
 
 
 
 
 
/*
run:
 
true
 
*/

 



answered Aug 13, 2023 by avibootz
0 votes
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        String[] strings = {"c", "c++", "java", "python"};
 
        System.out.println(Arrays.equals(Arrays.stream(strings).distinct().sorted().toArray(), strings));
    }
}
 
 
 
 
 
/*
run:
 
true
 
*/

 



answered Aug 13, 2023 by avibootz
...