Java Streams provide a wide range of operations and transformations that you can use to process your data. Let's explore some of the most common ones:
Filtering
The filter()
operation allows you to select elements from a stream based on a given predicate. For example, to filter out even numbers from a list:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]
Mapping
The map()
operation allows you to transform each element of a stream using a provided function. For example, to double the value of each number in a list:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> doubledNumbers = numbers.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
System.out.println(doubledNumbers); // Output: [2, 4, 6, 8, 10]
Sorting
The sorted()
operation allows you to sort the elements of a stream based on their natural order or a custom comparator. For example, to sort a list of strings in reverse alphabetical order:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<String> sortedNames = names.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println(sortedNames); // Output: [David, Charlie, Bob, Alice]
Reducing
The reduce()
operation allows you to combine the elements of a stream into a single value. For example, to calculate the sum of a list of numbers:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, Integer::sum);
System.out.println(sum); // Output: 15
Collecting
The collect()
operation allows you to gather the results of a stream pipeline into a new data structure, such as a List
, Set
, or Map
. For example, to collect the unique lengths of a list of strings:
List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");
Set<Integer> uniqueLengths = words.stream()
.map(String::length)
.collect(Collectors.toSet());
System.out.println(uniqueLengths); // Output: [5, 6, 4]
These are just a few examples of the many operations and transformations available in the Java Stream API. In the next section, we'll explore some practical examples and use cases for working with streams.