Pages

Verify List is sorted or not in java

Verify List is sorted or not in java ?

  • In java 8, we can use easily verify whether list is sorted or not using Stream interface.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class verifySorted {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(5);
list.add(1);
list.add(0);
list.add(3);
list.add(2);
System.out.println("Given List");
list.stream().forEach(System.out::print);
System.out.println("\nSorting the given list");
list.stream().sorted().forEach(System.out::print); // sort the given list
List<Integer> sortedlist = list.stream().sorted().collect(Collectors.toList());// sort given list and returns a
// sorted list
boolean isSorted = sortedlist.equals(list);// compare given list and sorted list
//list.stream().sorted().collect(Collectors.toList()).equals(list);// statement directly sort and compare given list and sorted list and returns boolean value
System.out.println("\nGiven list is sorted: " + isSorted);
}
}
Output:
list is sorted or not in java
sort list in java

We can also use Ordering class which is available in com.google.common.collect package.
We need to download com.google.common.collect jar or add maven dependency into your project.
import java.util.ArrayList;
import com.google.common.collect.Ordering;

public class verifySorted {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(5);
list.add(1);
list.add(0);
list.add(3);
list.add(2);
System.out.println("Given List");
list.stream().forEach(System.out::print);
boolean isSorted = Ordering.natural().isOrdered(list);
System.out.println("\nGiven list is sorted::"+isSorted);
}
}
Output:
list is sorted using Ordering class
list is sorted
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.