Terminal and intermediate stream methods in Java
Terminal stream methods
- findFirst() returns the first element;
- findAny() returns any matching element;
- collect() presenting results as collections and other data structures;
- count() returns the number of elements;
- anyMatch() returns true if the condition is met for at least one element;
- noneMatch() returns true if the condition is not met for any element;
- allMatch() returns true if the condition is met for all elements;
- min() returns the minimum element using the Comparator as a condition;
- max() returns the maximum element using the Comparator as a condition;
- forEach() applies a function to each object (parallel execution order is not guaranteed);
- forEachOrdered() applies a function to each object, maintaining the order of the elements;
- toArray() returns an array of values;
- reduce() allows you to execute aggregate functions and return a single result.
Additionally available for numeric streams:
- sum() returns the sum of all numbers;
- average() returns the arithmetic average of all numbers.
Intermediate stream methods
- filter() filters out records, returning only records that match the condition;
- skip() allows you to skip a certain number of elements at the beginning;
- distinct() returns a stream without duplicates (for the equals() method);
- map() transforms each element;
- peek() returns the same stream, applying a function to each element;
- limit() allows you to limit the selection to a certain number of first elements;
- sorted() allows you to sort the values either in natural order or by specifying a Comparator;
- mapToInt(), mapToDouble(), mapToLong() - analogs of map() that return a stream of numeric primitives;
- flatMap(), flatMapToInt(), flatMapToDouble(), flatMapToLong() - similar to map(), but they can create several elements from one element.
For numeric streams, the mapToObj() method is additionally available, which converts a numeric stream back to an object stream.
Examples of usage streams
Display 10 random numbers using forEach()
(new Random())
.ints()
.limit(10)
.forEach(System.out::println);
Display unique squares of numbers using the map() method
Stream
.of(1, 2, 3, 2, 1)
.map(s -> s * s)
.distinct()
.forEach(System.out::println);
Display the number of empty lines using the filter() method
System.out.println(
Stream
.of("Hello", "", ", ", "world", "!")
.filter(String::isEmpty)
.count());
Display 10 random numbers in ascending order
(new Random())
.ints()
.limit(10)
.sorted()
.forEach(System.out::println);
Find the maximum number in a set
Stream
.of(5, 3, 4, 55, 2)
.mapToInt(a -> a)
.max()
.getAsInt(); // 55
Find the minimum number in a set
Stream
.of(5, 3, 4, 55, 2)
.mapToInt(a -> a)
.min()
.getAsInt(); // 2
Get the sum of all numbers in a set
Stream
.of(5, 3, 4, 55, 2)
.mapToInt()
.sum(); // 69
Get the average of all numbers
Stream
.of(5, 3, 4, 55, 2)
.mapToInt(a -> a)
.average()
.getAsDouble(); // 13.8
Read also:
Comments
Post a Comment