Learn Java 8 Stream Intermediate And Terminal Operations with Example
Java is Object Oriented Programming language, being object-oriented is not bad, but it brings a lot of verbosity to the program. Java 8 introduced new libraries and programming styles, for example, functional interfaces, lambda expressions, and streams. These bring functional-style programming to the object-oriented programming capabilities of Java. Java Functional Interface and Lambda Expression help us write smaller and cleaner code by removing much boilerplate code.
Java Stream Intermediate operations and Terminal operations
The intermediate operation will transform a stream into another stream, such as a map(MapperFn) or a filter(Predicate).
The Terminal operation will produce a result or side-effect, such as count() or forEach(Consumer).
All intermediate operations will NOT be executed without a terminal operation at the end. So the pattern will be:
stream()
.intemediateOperation1()
.intemediateOperation2()
.......................
.intemediateOperationN()
.terminalOperation();
Example 1: filter() and collect() example - Filter all the users whose age is above 30
import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;
// Java 8 Streams filter() and collect() example.// Filters all the users whose age above 30public class DemoApplication {
public static void main(String[] args) {
User usr1 = new User("1", "alpha", 58); User usr2 = new User("2", "beta", 48); User usr3 = new User("3", "gama", 22); User usr4 = new User("4", "tesla", 30); User usr5 = new User("5", "pekka", 12);
List<User> userList = new ArrayList<User>(); userList.add(usr1); userList.add(usr2); userList.add(usr3); userList.add(usr4); userList.add(usr5);
// Filters all the users with age above 30 List<User> ageGreaterThan30 = userList.stream(). filter(u -> u.getAge() > 30). collect(Collectors.toList()); System.out.println(ageGreaterThan30);
}
}
class User { String id; String name; Integer age;
String getId() { return id; }
void setId(String id) { this.id = id; }
String getName() { return name; }
void setName(String name) { this.name = name; }
Integer getAge() { return age; }
void setAge(Integer age) { this.age = age; }
User(String id, String name, Integer age) { super(); this.id = id; this.name = name; this.age = age; }
@Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; }}
The filter() is an intermediate operation that reads the data from a stream and returns an incipient stream after transforming the data predicated on the given condition.
The collect() is a terminal operation mostly used to collect the stream elements to a collection.
The collect() is a terminal operation mostly used to collect the stream elements to a collection.
Example 2: min() and max() example - Find smallest and largest number
import java.util.Arrays;import java.util.List;import java.util.Optional;
// Java 8 Streams min() and max() example.// Finding Smallest Element and Largest Elementpublic class DemoApplication {
public static void main(String[] args) {
List<Integer> numbers = Arrays. asList(3, 6, 11, 8, 44, 33, 8);
// Finding Smallest Number Optional<Integer> minNumber = numbers.stream() .min((i, j) -> i.compareTo(j)); System.out.println("Smallest number: " + minNumber.get());
// Finding Largest Number Optional<Integer> largestNumber = numbers.stream() .max((i, j) -> i.compareTo(j)); System.out.println("Largest number: " + largestNumber.get());
}}
The min() method returns the minimum element in the designated collection and the max () returns the maximum element in the designated collection, according to the natural ordering of its elements.
Example 3: count() example - Counting the number of elements in a List
import java.util.Arrays;import java.util.List;
// Java 8 Streams count() example// Counting number of elements in a Listpublic class DemoApplication {
public static void main(String[] args) {
List<Integer> numbers = Arrays. asList(3, 6, 11, 8, 44, 33, 8);
// Using count() to count the number // of elements long total = numbers.stream().count(); System.out.println("Total elemnts in a List: " + total);
}}
The count() returns a long value indicating the number of matching items in the stream.
Example 4: distinct() example - Finding Distinct Numbers
import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;
// Java 8 Streams distict() example// Finding Distinct Numberspublic class DemoApplication {
public static void main(String[] args) {
List<Integer> numbers = Arrays. asList(33, 6, 11, 8, 44, 33, 8);
// Find all distinct numbers List<Integer> distinctElements = numbers.stream() .distinct() .collect(Collectors.toList()); System.out.println(distinctElements);
}}
The distinct() returns a new stream consisting of the distinct elements from the given stream.
Example 5: map() example - Converting a List of Integers to a List of String
import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;
// Java 8 Streams map() example// Converting a List of Integers to a List of String public class DemoApplication {
public static void main(String[] args) {
List<Integer> numbers = Arrays. asList(33, 6, 11, 8, 44, 33, 8);
//Converting a List of Integers to a List of String List<String> strNumbers = numbers.stream(). map(String::valueOf) .collect(Collectors.toList()); System.out.println(strNumbers);
}}
The map() is used to convert the Stream of one type to another.
Example 6: sorted() example - Sort a List
import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.Comparator;
// Sort a List with stream.sorted()public class DemoApplication {
public static void main(String[] args) {
List<Integer> numbers = Arrays. asList(13, 6, 11, 28, 44, 33, 8);
//Sort a List with stream.sorted() List<Integer> sortedList = numbers.stream(). sorted() .collect(Collectors.toList()); System.out.println(sortedList);
//Sort a List reverseOrder with stream.sorted() List<Integer> sortedListreverseOrder = numbers.stream(). sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); System.out.println(sortedListreverseOrder);
}}
Stream sorted() returns a stream consisting of the elements of this stream, sorted according to the natural order.
Example 7: reduce() example - Finding sum of all elements
import java.util.Arrays;import java.util.List;
// Finding sum of all elementspublic class DemoApplication {
public static void main(String[] args) {
List<Integer> numbers = Arrays. asList(13, 6, 11, 28, 44, 33, 8);
// Finding sum of all elements int sum = numbers.stream().reduce(0, (element1, element2) -> element1 + element2); System.out.println("Sum= " + sum);
}}
Example 8: forEach() example - Iterate the elements
import java.util.Arrays;import java.util.List;
// Iterate the elements using forEach()public class DemoApplication {
public static void main(String[] args) {
List<Integer> numbers = Arrays. asList(13, 6, 11, 28, 44, 33, 8);
//Print the elements using forEach() numbers.forEach(System.out::println);
}}