15 must-know Stream API methods for Java developers
Learning Java Stream API can help developers write concise functional code in processing collections. This guide explores 12 stream API methods that include filter(),map(),reduce() which is important when working with large collections of a data set.
Don’t forget to bookmark and share this article 🙂
It is very important to identity the two group that Stream API can be group into one is Intermediate Operation and the other is Terminal Operation.
Intermediate operations: These are operations that return a new stream as a result. They do not modify the original stream but rather create a new stream that can be used for further processing.
filter
(Predicate<T> predicate): This operation takes a predicate that determines whether an element should be included in the new stream or not.List<String> words = Arrays.asList("apple", "banana", "orange", "pear", "peach"); Stream<String> longWords = words.stream().filter(w -> w.length() > 5); longWords.forEach(System.out::println);
map
(Function<T, R> mapper): This operation takes a function that transforms each element of the stream into a new element of a different type.List<String> words = Arrays.asList("apple", "banana", "orange", "pear", "peach"); Stream<Integer> wordLengths = words.stream().map(String::length); wordLengths.forEach(System.out::println); // Output: 5 6 6 4 5
flatMap
(Collection ) This method is used to flatten a stream of collections or arrays into a single stream.List<List<Integer>> numbers = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4, 5), Arrays.asList(6, 7, 8, 9)); Stream<Integer> flattenedNumbers = numbers.stream().flatMap(Collection::stream); flattenedNumbers.forEach(System.out::println); // Output: 1 2 3 4 5 6 7 8 9
distinct
: This method is used to remove duplicate elements from a stream.List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 3, 3, 4, 4, 4, 4); Stream<Integer> distinctNumbers = numbers.stream().distinct(); distinctNumbers.forEach(System.out::println); // Output: 1 2 3 4
sorted()
: This operation sorts the elements of the stream based on their natural ordering or a provided comparator.List<String> fruits = Arrays.asList("apple", "pear", "orange", "banana"); Stream<String> sortedFruits = fruits.stream().sorted(); sortedFruits.forEach(System.out::println); // Output: apple banana orange pear
peek
: This method is used to act on each element in a stream without modifying the stream.List<String> words = Arrays.asList("apple", "banana", "orange", "pear", "peach"); words.stream() .filter(w -> w.length() > 5) .peek(w -> System.out.println("Filtered word: " + w)) .map(String::toUpperCase) .forEach(System.out::println);
limit
(long maxSize): This operation returns a new stream that contains at most the specified number of elements.List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); Stream<Integer> limitedNumbers = numbers.stream().limit(3); limitedNumbers.forEach(System.out::println); // Output: 1 2 3
Terminal operations: are operations that produce a non-stream result, such as a value or a side effect. They mark the end of the stream processing and cannot be followed by any more stream operations.
forEach
:(Consumer<T> action): This operation applies the specified action to each element of the stream.List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); numbers.stream().forEach(n -> System.out.println(n));
toArray
: This method is used to convert a stream into an array.List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); Integer[] numbersArray = numbers.stream().toArray(Integer[]::new); System.out.println(Arrays.toString(numbersArray)); // Output: [1, 2, 3, 4, 5]
reduce
(T identity, BinaryOperator<T> accumulator): This operation combines the elements of the stream into a single result using the provided binary operator and initial value.List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.stream().reduce(0, Integer::sum); System.out.println(sum); // Output: 15sample
collect
(Collector<T, A, R> collector): This operation collects the elements of the stream into a result container specified by the provided collector.min & max
: These methods are used to find the minimum and maximum elements in a stream, according to a specified comparator.List<Integer> numbers = Arrays.asList(3, 6, 1, 8, 4); Optional<Integer> minNumber = numbers.stream().min(Integer::compareTo); System.out.println(minNumber); // Output: 1 Optional<Integer> maxNumber = numbers.stream().max(Integer::compareTo); System.out.println(maxNumber); // Output: 8
count
:This method is used to count the number of elements in a stream.// Count the number of elements in a stream List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); long count = numbers.stream().count(); System.out.println(count); // Output: 5
anyMatch , allMatch , noneMatch
: These methods are used to check whether any, all, or none of the elements in a stream match a given predicate.List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); boolean anyMatch = numbers.stream().anyMatch(n -> n > 3); System.out.println(anyMatch); // Output: true boolean allMatch = numbers.stream().allMatch(n -> n < 10); System.out.println(allMatch); // Output: true boolean noneMatch = numbers.stream().noneMatch(n -> n < 0); System.out.println(noneMatch); // Output: true
findAny , findFirst
: These methods are used to find the first or any element in a stream that matches a given predicate.// Find any element in a stream List<String> words = Arrays.asList("apple", "banana", "cherry"); Optional<String> anyWord = words.stream().findAny(); if (anyWord.isPresent()) { System.out.println(anyWord.get()); // Output: "apple" or "banana" or "cherry" } else { System.out.println("No word found"); } // Find the first element in a stream List<Integer> nums = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5); Optional<Integer> firstNum = nums.stream().findFirst(); if (firstNum.isPresent()) { System.out.println(firstNum.get()); // Output: 3 } else { System.out.println("No number found"); }
Thanks for reading,Don’t forget to bookmark and share this article 🙂
Subscribe to my newsletter
Read articles from Sylvester Amaechi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by