Welcome to our comprehensive Java Stream sorted() tutorial! This lesson is designed for both beginners and intermediate learners who want to understand how to sort collections using Java Stream API.
Java Stream API is a part of Java 8 that allows us to work with collections in a more functional way. It provides a rich set of methods to filter, map, and reduce elements in a collection, making our code more concise and expressive.
The sorted() method in Java Stream API returns a new Stream that contains the sorted elements of the original Stream. It sorts the elements in ascending order by default, but you can specify a custom Comparator if needed.
Before diving into the sorted() method, it's essential to have a basic understanding of:
Let's start with a simple example where we sort a List of integers.
List<Integer> numbers = Arrays.asList(12, 1, 56, 8, 34, 21, 9, 67);
List<Integer> sortedNumbers = numbers.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(sortedNumbers); // Output: [1, 8, 9, 12, 21, 34, 56, 67]In this example, we create a List of integers and create a new Stream from it. We then call the sorted() method to sort the elements, and finally, we collect the sorted elements back into a List using the collect() method.
Suppose you want to sort a list of Strings based on their lengths, and if the lengths are the same, you want to sort them alphabetically.
List<String> strings = Arrays.asList("Apple", "banana", "cherry", "orange", "ApplePie");
List<String> sortedStrings = strings.stream()
.sorted(Comparator.comparingInt(s -> s.length())
.thenComparing(String::compareTo))
.collect(Collectors.toList());
System.out.println(sortedStrings); // Output: [orange, banana, cherry, Apple, ApplePie]In this example, we create a List of Strings and create a new Stream from it. We then define a Comparator that first compares the lengths of the Strings and, if the lengths are the same, it compares the Strings alphabetically using the compareTo() method.
Which method in Java Stream API returns a new Stream that contains the sorted elements of the original Stream?
That's it for this lesson on Java Stream sorted()! Stay tuned for more in-depth tutorials on Java Stream API. Happy coding! 💻🤖