Use Stream API for Sorted Check
In this step, we will explore a more modern and often more concise way to check if a list is sorted using Java's Stream API. The Stream API, introduced in Java 8, provides a functional approach to processing collections of data.
We will modify our previous program to include a method that checks if the list is sorted in ascending order using streams.
Open the ListComparison.java
file in the WebIDE editor. Add a new method called isSortedAscending
to the ListComparison
class, outside of the main
method but inside the ListComparison
class curly braces {}
.
Here's the updated code for ListComparison.java
:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class ListComparison {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(2);
numbers.add(4);
numbers.add(5);
System.out.println("Original list: " + numbers);
// Check if the list is sorted using the new method
boolean sorted = isSortedAscending(numbers);
if (sorted) {
System.out.println("The list is sorted in ascending order.");
} else {
System.out.println("The list is NOT sorted in ascending order.");
}
// The previous loop for comparison is removed for simplicity in this step
// but you can keep it if you want to see both methods in action.
}
// Method to check if the list is sorted in ascending order using Streams
public static boolean isSortedAscending(List<Integer> list) {
if (list == null || list.size() <= 1) {
return true; // An empty or single-element list is considered sorted
}
return IntStream.range(0, list.size() - 1)
.allMatch(i -> list.get(i).compareTo(list.get(i + 1)) <= 0);
}
}
Let's look at the new parts:
import java.util.stream.IntStream;
: This imports the IntStream
class, which is useful for working with sequences of integers in streams.
public static boolean isSortedAscending(List<Integer> list)
: This declares a new static method named isSortedAscending
that takes a List
of Integer
and returns a boolean
(true if sorted, false otherwise).
if (list == null || list.size() <= 1)
: This handles edge cases: an empty list or a list with one element is always considered sorted.
IntStream.range(0, list.size() - 1)
: This creates a stream of integers from 0 up to (but not including) list.size() - 1
. These integers represent the indices of the list elements we want to compare.
.allMatch(i -> list.get(i).compareTo(list.get(i + 1)) <= 0)
: This is the core of the stream operation.
allMatch()
is a terminal operation that checks if all elements in the stream match a given condition.
i -> list.get(i).compareTo(list.get(i + 1)) <= 0
is a lambda expression that defines the condition. For each index i
from the IntStream
, it gets the element at index i
and the element at index i + 1
.
list.get(i).compareTo(list.get(i + 1))
compares the two elements. compareTo
returns a negative integer if the first element is less than the second, zero if they are equal, and a positive integer if the first element is greater than the second.
<= 0
checks if the result of compareTo
is less than or equal to zero. This condition is true if the current element is less than or equal to the next element, which is the definition of ascending order.
allMatch
returns true
only if this condition is true for all adjacent pairs in the list.
Save the ListComparison.java
file.
Now, compile and run the updated program in the Terminal:
javac ListComparison.java
java ListComparison
The output should now indicate whether the list is sorted in ascending order based on the isSortedAscending
method:
Original list: [1, 3, 2, 4, 5]
The list is NOT sorted in ascending order.
Modify the list in the main
method to be sorted, for example:
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
Save the file, compile, and run again. The output should now be:
Original list: [1, 2, 3, 4, 5]
The list is sorted in ascending order.
This demonstrates how to use the Stream API to perform a concise check for ascending order.