Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 

 3 Answer(s)

  • Please find a sample code snippet :

    
    import java.util.ArrayList;
    
    public class ArrayListDemo {
        // Here is the code to check if array list is sorted in Ascending order or not
        boolean checkSorting(ArrayList< String > arraylist){
            boolean isSorted=true;
            for(int i=1;i < arraylist.size();i++){
                if(arraylist.get(i-1).compareTo(arraylist.get(i)) > 0){
                    isSorted= false;
                    break;
                }
            }
            return isSorted;
        }
        public static void main(String[] args) {
            ArrayList < String > al=new ArrayList < String >();
            al.add("abc");
            al.add("xyz");
            al.add("mnp");
            ArrayListDemo alDemo=new ArrayListDemo();
            System.out.println("Is Sorted in ascending:"+alDemo.checkSorting(al));
    
        }
    
    }
    

    Output: Is Sorted in ascending:false

  • HI try doing this 
    1. public static boolean isSorted(int[] a) {
    2. if (a == null || a. length <= 1) { return true;
    3. return IntStream. range(0, a. length - 1). noneMatch(i -> a[i] > a[i + 1]); }
    4. public static void main(String[] args) {
    5. System. out. println(isSorted(a)); // true. }
  • You just need to write the below method in which you will pass your String Arraylist:

    /**
     * This method will return false if you list is not sorted
     * @param list
     * @return
     */
    public boolean isSorted(List<String> list)
    {
        boolean sorted = true;        
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i-1).compareTo(list.get(i)) > 0) sorted = false;
        }
    
        return sorted;
    }
    

    Hope this will help you :)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: