Introduction
Java 8 introduced the Stream API, which provides a functional approach to processing sequences of elements. Streams support operations like filtering, mapping, reducing, and collecting, making it easier to perform complex data manipulations on collections in a concise, readable, and efficient way. Streams can work with collections like List
, Set
, and even arrays.
In this tutorial, we will cover 15 practical examples of the Java 8 Stream API.
Table of Contents
- Example 1: Create a Stream from a List
- Example 2: Filter Elements in a Stream
- Example 3: Map Elements in a Stream
- Example 4: Stream
forEach()
to Print Elements - Example 5: Stream
collect()
to Convert to a List - Example 6: Sort Elements in a Stream
- Example 7: Reduce a Stream to a Single Value
- Example 8: Count Elements in a Stream
- Example 9: Limit the Stream Size
- Example 10: Skip Elements in a Stream
- Example 11: FlatMap Example (Flattening Nested Lists)
- Example 12: Find the First Element in a Stream
- Example 13: Check if Any Match in a Stream
- Example 14: Grouping by using Collectors
- Example 15: Stream Parallel Processing
Example 1: Create a Stream from a List
The most common way to create a stream is by using a collection like a List
.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class CreateStreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Amit", "Deepa", "Rahul", "Suresh");
// Create a stream from the list
Stream<String> stream = names.stream();
// Print each element using forEach
stream.forEach(System.out::println);
}
}
Output
Amit
Deepa
Rahul
Suresh
Explanation
- We use
names.stream()
to create a stream from the list. - The
forEach()
method prints each element of the stream.
Example 2: Filter Elements in a Stream
You can filter elements in a stream based on a condition using the filter()
method.
Code Example
import java.util.Arrays;
import java.util.List;
public class FilterStreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Amit", "Deepa", "Rahul", "Suresh");
// Filter names that start with 'A'
names.stream()
.filter(name -> name.startsWith("A"))
.forEach(System.out::println);
}
}
Output
Amit
Explanation
- We use the
filter()
method to keep only the names that start with "A".
Example 3: Map Elements in a Stream
The map()
function is used to transform each element in the stream.
Code Example
import java.util.Arrays;
import java.util.List;
public class MapStreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Amit", "Deepa", "Rahul", "Suresh");
// Convert all names to uppercase
names.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
Output
AMIT
DEEPA
RAHUL
SURESH
Explanation
- The
map()
function transforms each element to uppercase usingString::toUpperCase
.
Example 4: Stream forEach()
to Print Elements
The forEach()
method is used to perform an action on each element of the stream.
Code Example
import java.util.Arrays;
import java.util.List;
public class StreamForEachExample {
public static void main(String[] args) {
List<String> cities = Arrays.asList("Mumbai", "Delhi", "Bangalore");
// Print each city
cities.stream().forEach(System.out::println);
}
}
Output
Mumbai
Delhi
Bangalore
Explanation
- The
forEach()
method appliesSystem.out::println
to print each element of the stream.
Example 5: Stream collect()
to Convert to a List
The collect()
method collects the stream's elements into a collection like a List
.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectStreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Amit", "Deepa", "Rahul", "Suresh");
// Collect names that start with 'D' into a List
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("D"))
.collect(Collectors.toList());
System.out.println(filteredNames);
}
}
Output
[Deepa]
Explanation
- The
collect(Collectors.toList())
collects the filtered names into a new list.
Example 6: Sort Elements in a Stream
The sorted()
method sorts the elements of the stream.
Code Example
import java.util.Arrays;
import java.util.List;
public class SortedStreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Suresh", "Amit", "Deepa", "Rahul");
// Sort and print names
names.stream()
.sorted()
.forEach(System.out::println);
}
}
Output
Amit
Deepa
Rahul
Suresh
Explanation
- The
sorted()
method sorts the names in natural order (alphabetical order).
Example 7: Reduce a Stream to a Single Value
The reduce()
method is used to reduce a stream to a single value.
Code Example
import java.util.Arrays;
import java.util.List;
public class ReduceStreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Sum of all numbers using reduce()
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println("Sum: " + sum);
}
}
Output
Sum: 15
Explanation
- The
reduce()
method adds all elements of the stream, starting with 0.
Example 8: Count Elements in a Stream
The count()
method returns the number of elements in the stream.
Code Example
import java.util.Arrays;
import java.util.List;
public class CountStreamExample {
public static void main(String[] args) {
List<String> cities = Arrays.asList("Mumbai", "Delhi", "Bangalore");
// Count the number of cities
long count = cities.stream().count();
System.out.println("Total cities: " + count);
}
}
Output
Total cities: 3
Explanation
- The
count()
method returns the total number of elements in the stream.
Example 9: Limit the Stream Size
The limit()
method limits the number of elements in the stream.
Code Example
import java.util.Arrays;
import java.util.List;
public class LimitStreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
// Limit the stream to 3 elements
numbers.stream()
.limit(3)
.forEach(System.out::println);
}
}
Output
1
2
3
Explanation
- The
limit()
method limits the stream to the first 3 elements.
Example 10: Skip Elements in a Stream
The skip()
method skips the first n elements in a stream.
Code Example
import java.util.Arrays;
import java.util.List;
public class SkipStreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
// Skip the first 2 elements
numbers.stream()
.skip(2)
.forEach(System.out::println);
}
}
Output
3
4
5
6
Explanation
- The
skip()
method skips the first 2 elements and processes the remaining ones.
Example 11: FlatMap Example (Flattening Nested Lists)
The flatMap()
method is used to flatten nested collections like lists of lists.
Code Example
import java.util.Arrays;
import java.util.List;
public class FlatMapStreamExample {
public static void main(String[] args) {
List<List<String>> nestedList = Arrays.asList(
Arrays.asList("Amit", "Rahul"),
Arrays.asList("Deepa", "Suresh")
);
// Flatten the nested list and print all names
nestedList.stream()
.flatMap(List::stream)
.forEach(System.out::println);
}
}
Output
Amit
Rahul
Deepa
Suresh
Explanation
- The
flatMap()
method is used to flatten the nested lists into a single stream of names.
Example 12: Find the First Element in a Stream
The findFirst()
method returns the first element of the stream.
Code Example
import java.util.Arrays;
import java.util.List;
public class FindFirstStreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Amit", "Deepa", "Rahul", "Suresh");
// Find the first name in the list
String firstName = names.stream().findFirst().orElse("No name");
System.out.println("First name: " + firstName);
}
}
Output
First name: Amit
Explanation
- The
findFirst()
method returns the first element of the stream or a default value if the stream is empty.
Example 13: Check if Any Match in a Stream
The anyMatch()
method checks if any element in the stream matches a condition.
Code Example
import java.util.Arrays;
import java.util.List;
public class AnyMatchStreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Amit", "Deepa", "Rahul", "Suresh");
// Check if any name starts with 'D'
boolean anyMatch = names.stream()
.anyMatch(name -> name.startsWith("D"));
System.out.println("Any name starts with D? " + anyMatch);
}
}
Output
Any name starts with D? true
Explanation
- The
anyMatch()
method returnstrue
if any element matches the condition (starting with "D").
Example 14: Grouping by using Collectors
The Collectors.groupingBy()
method is used to group elements in a stream based on a classifier function.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GroupByStreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Amit", "Deepa", "Rahul", "Akhil");
// Group names by the first letter
Map<Character, List<String>> groupedByLetter = names.stream()
.collect(Collectors.groupingBy(name -> name.charAt(0)));
System.out.println(groupedByLetter);
}
}
Output
{A=[Amit, Akhil], D=[Deepa], R=[Rahul]}
Explanation
- The
groupingBy()
method groups the names by their first character.
Example 15: Stream Parallel Processing
The parallelStream()
method allows processing the stream in parallel, enabling multi-threading.
Code Example
import java.util.Arrays;
import java.util.List;
public class ParallelStreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Amit", "Deepa", "Rahul", "Suresh");
// Process names in parallel
names.parallelStream().forEach(name -> System.out.println(name + " - " + Thread.currentThread().getName()));
}
}
Output (Order might vary)
Amit - ForkJoinPool.commonPool-worker-1
Deepa - main
Rahul - ForkJoinPool.commonPool-worker-3
Suresh - ForkJoinPool.commonPool-worker-2
Explanation
- The
parallelStream()
method enables parallel processing of elements, which can improve performance for large datasets.
Conclusion
The Java 8 Stream API provides powerful and flexible ways to work with collections and data streams. These 15 examples cover common operations like filtering, mapping, reducing, and collecting elements. Streams simplify the code, making it more readable and concise, and they allow developers to harness functional programming techniques in Java.
Comments
Post a Comment
Leave Comment