-
How to check if string arraylist is sorted?
about 10 years ago
-
about 10 years ago
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
-
over 2 years ago
HI try doing this- public static boolean isSorted(int[] a) {
- if (a == null || a. length <= 1) { return true;
- return IntStream. range(0, a. length - 1). noneMatch(i -> a[i] > a[i + 1]); }
- public static void main(String[] args) {
- System. out. println(isSorted(a)); // true. }
-
-
about 10 years ago
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 :)
-
3 Answer(s)