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

 2 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

  • 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: