Lambda Expression — Stream API — JAVA 8
Lambda expressions and Stream API are two important features introduced in Java 8 that simplify and enhance the way we write code. Lambda expressions provide a concise way to represent anonymous functions, while Stream API provides a fluent, functional-style way to process collections of data.
Lambda Expressions
A lambda expression is a compact way to represent an anonymous function. It can be used whenever an interface with a single abstract method, also known as a functional interface, is expected. The syntax of a lambda expression consists of the parameter list, the arrow operator ->, and the body of the function.
Get Naeem Siddiq’s stories in your inbox
Join Medium for free to get updates from this writer.
Here’s an example of a lambda expression that takes two integers and returns their sum:
(int x, int y) -> x + yThis lambda expression can be used to implement a functional interface that has a method with the following signature:
int sum(int x, int y);Here’s an example of using the lambda expression to call the sum method:
int result = sum((int x, int y) -> x + y);Advantages of Lambda Expressions
- Concise syntax: Lambda expressions provide a compact syntax that can reduce the amount of boilerplate code required for anonymous inner classes.
- Readable code: Lambda expressions can make code more readable by expressing the intent of the code more clearly.
- Functional programming: Lambda expressions enable functional programming, which promotes the use of immutable data and pure functions.
- Parallel processing: Lambda expressions are compatible with the Stream API, which allows for easy parallel processing of data.
Stream API
The Stream API is a powerful feature introduced in Java 8 that provides a fluent, functional-style way to process collections of data. A stream is a sequence of elements that can be processed in parallel or in a pipeline of operations.
Creating a Stream
Streams can be created from various sources such as collections, arrays, and I/O channels. Here are some examples:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> stream1 = numbers.stream(); // create a stream from a collection
Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5); // create a stream from individual elements
IntStream stream3 = IntStream.range(1, 6); // create a stream of integers
Stream<String> stream4 = Files.lines(Paths.get("file.txt")); // create a stream from a fileIntermediate Operations
Intermediate operations are operations that transform a stream into another stream. These operations are lazy, meaning that they do not perform any computation until a terminal operation is applied.
Filtering
The filter method filters a stream based on a predicate. Here's an example that filters a stream of integers to include only even numbers:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> evenNumbers = numbers.stream().filter(n -> n % 2 == 0);
evenNumbers.forEach(System.out::println); // prints 2 4Mapping
The map method transforms each element in a stream based on a function. Here's an example that converts a stream of strings to a stream of their lengths:
List<String> words = Arrays.asList("hello", "world", "java");
Stream<Integer> lengths = words.stream().map(String::length);
lengths.forEach(System.out::println); // prints 5 5 4FlatMapping
The flatMap method flattens a stream of collections or arrays into a stream of their elements. Here's an example that flattens a stream of lists:
List<List<Integer>> numbers = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5, 6)
);
Stream<Integer> flattenedNumbers = numbers.stream().flatMap(List::stream);
flattenedNumbers.forEach(System.out::println); // prints 1 2 3 4 5 6Sorting
The sorted method sorts a stream based on a comparator. Here's an example that sorts a stream of strings in ascending order:
List<String> words = Arrays.asList("world", "java", "hello");
Stream<String> sortedWords = words.stream().sorted();
sortedWords.forEach(System.out::println); // prints hello java worldTerminal Operations
Terminal operations are operations that produce a result or a side-effect. These operations trigger the execution of intermediate operations.
Collecting
The collect method collects the elements of a stream into a collection. Here's an example that collects a stream of strings into a list:
List<String> words = Arrays.asList("hello", "world", "java");
List<String> collectedWords = words.stream().collect(Collectors.toList());
System.out.println(collectedWords); // prints [hello, world, java]Reducing
The reduce method reduces the elements of a stream into a single value. Here's an example that reduces a stream of integers to their sum:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().reduce(0, (x, y) -> x + y);
System.out.println(sum); // prints 15Counting
The count method counts the number of elements in a stream. Here's an example that counts the number of even numbers in a stream:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
long count = numbers.stream().filter(n -> n % 2 == 0).count();
System.out.println(count); // prints 2ForEach
The forEach method performs a side-effect on each element of a stream. Here's an example that prints each element of a stream:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream().forEach(System.out::println); // prints 1 2 3 4 5Putting It All Together
Here’s an example that combines the intermediate and terminal operations to filter, map, and collect a stream of strings that start with a vowel into a list:
List<String> words = Arrays.asList("apple", "banana", "cat", "egg", "orange");
List<String> collectedWords = words.stream()
.filter(s -> "aeiou".indexOf(s.charAt(0)) >= 0)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(collectedWords); // prints [APPLE, EGG, ORANGE]In this example, the filter method filters the stream to include only strings that start with a vowel, the map method transforms each string to uppercase, and the collect method collects the transformed strings into a list.
Conclusion
In this blog, we covered the basic methods of the Java 8 Stream API and provided coding examples for each method. We also explained lambda expressions and how they can be used with streams to write concise code. Hopefully, this log has provided a good introduction to the Stream API and lambda expressions in Java 8.







