JEWEL FUEL 999 Pure Silver Radha Krishna Stand And German Silver Tulsi Plant Gift Set
In the previous journal entry “Understanding Java 8 Streams with Examples” we have looked at the core concepts of Java 8 Streams API with some examples. Then we took a look at the Intermediate operation methods of Java 8 Streams. Now, in this journal we will take a look at some more examples of Java 8 Stream operations: Terminal.
A terminal operation should always be the last operation in a Stream pipeline.
Terminal operations are executed eagerly i.e they process all the elements in the stream before returning the result.
Java 8 Streams Terminal Operation Examples
Let’s have a look at some of the basic use cases of terminal operation methods provided by Stream API.
- forEach()
- toArray()
- reduce()
- collect()
- count()
- max()
- min()
- anyMatch()
- allMatch()
- noneMatch()
- findFirst()
- findAny()
forEach(): Perform an action for each element in the stream. It is basically a simplified inline way for writing a for loop.
Java Stream forEach() Example:
Stream<String> names = Stream.of("Kirsten", "John", "Philips");
names.forEach(name -> System.out.println(name));
toArray(): As shown in the example of the journal “Understanding Java 8 Stream“, it is used to create an Array from a Stream.
Java 8 Stream toArray() Example:
Stream<Integer> intStream = Stream.of(1,2,3,4); Integer[] intArray = intStream.toArray(Integer[]::new); System.out.println(Arrays.toString(intArray)); //prints [1, 2, 3, 4]
reduce(): A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result.
Java 8 Stream reduce() Example:
Stream<Integer> intStream = Stream.of(1,2,3,4); int sum = intStream.reduce(0, (x,y) -> x+y); // OR int sum = intStream.reduce(0, Integer::sum);
collect(): As shown in the example of the journal “Understanding Java 8 Stream“, we can use java Stream collect() method to accumulate elements in a stream into a container such as a collection.
Java 8 Stream collect() Example:
Stream<Integer> intStream = Stream.of(1,2,3,4);
List<Integer> intList = intStream.collect(Collectors.toList());
System.out.println(intList);
//prints [1, 2, 3, 4]
//stream is closed, so we need to create it again
intStream = Stream.of(1,2,3,4);
Map<Integer,Integer> intMap = intStream.collect(Collectors.toMap(i -> i, i -> i+10));
System.out.println(intMap);
//prints {1=11, 2=12, 3=13, 4=14}
count(): Returns the count of the total number of items availabe in the Stream.
Java 8 Stream count() Example:
Stream<Integer> intStream = Stream.of(1,2,3,4);
System.out.println("Total Number of Elements: " + intStream.count());
// OUTPUT
4
max(): A special reduction operation that returns an Optional describing the maximum element of the stream according to the provided Comparator.
Java 8 Stream max() Example:
public class Person {
String name;
int age;
//Constructors and Getters/Setters are omitted...
}
public class Java8StreamMax {
public static void main(String[] args) {
List<Person> personList = Arrays.asList(
new Person("Smith", 37),
new Person("John", 24),
new Person("Kirsten", 33)
);
//Find Oldest Person
final Comparator<Person> comp = (p1, p2) -> Integer.compare( p1.getAge(), p2.getAge());
Person result = personList.stream() // Convert to steam
.max(comp) // Find the Max using the Comparator
.get();
System.out.println(result);
}
}
min(): A special reduction operation that returns an Optional describing the minimum element of this stream according to the provided Comparator.
Java 8 Stream min() Example:
Taking the same example as above for finding the max(), we will simply replace the method name max() with min().
.
.
.
Person result = personList.stream() // Convert to steam
.min(comp) // Find the Min using the Comparator
.get();
.
.
.
anyMatch(): Method to find out whether at least one of the elements in the stream matches a given predicate.
Java 8 Stream anyMatch() Example:
Stream<String> names = Stream.of("Kirsten", "John", "Philips");
boolean moreThan6Chars = names.anyMatch(s -> s.length() > 6);
System.out.println("Are names with more than 6 Characters? " + moreThan6Chars);
// OUTPUT
Are names with more than 6 Characters? true
allMatch(): Method to find out whether all the elements in the stream matches a given predicate.
Java 8 Stream allMatch() Example:
Using the same example as above, we can find out whether the length of the names are equal to or more than 4 characters.
. . . boolean equalToMoreThan4Chars = names.allMatch(s -> s.length() >= 4); . . .
noneMatch(): Method to find out that no elements in the stream match a given predicate.
Java 8 Stream noneMatch() Example:
Again using the same example as above, we can find out the names length should not be less than 4 characters.
. . . boolean noLessThan4Chars = namesNoneMatch.noneMatch(s -> s.length() < 4); . . .
findFirst(): Method to find the first element in the stream.
Java 8 Stream findFirst() Example:
Stream<String> names = Stream.of("Kirsten", "John", "Philips");
Optional<String> name = names.filter(i -> i.startsWith("J")).findFirst();
if(name.isPresent()) {
System.out.println("First Name starting with J = " + name.get());
}
// OUTPUT
John
findAny(): Method to fetch any element of the stream satisfying a given criteria.
Java 8 Stream findAny() Example:
Stream<String> names = Stream.of("Kirsten", "John", "Philips", "Kentucky");
Optional<String> name = names.filter(i -> i.startsWith("K")).findAny();
if ( name.isPresent() ) {
System.out.println("findAny Name Starting with K: " + name.get());
}
