In Java, streams provide a powerful way to manipulate collections of data. They allow us to perform various operations on a collection such as filtering elements, mapping values, and reducing the stream to a single value. In this article, we'll explore these three fundamental operations in detail.
Filtering stream elements is a common task when working with collections. The filter
operation takes a predicate as an argument and returns a new stream containing only elements that match the given criteria.
Here's an example that filters out even numbers from a list:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // Output: [2, 4, 6]
In this example, we create a stream from the list of numbers and use the filter
operation to keep only the elements that are divisible by 2. Finally, we collect the filtered elements into a new list.
Mapping is the process of transforming each element of a stream into another value or form. The map
operation allows us to apply a function to each element of the stream, resulting in a new stream of transformed elements.
Let's say we have a list of strings and we want to convert each string to uppercase:
List<String> names = Arrays.asList("John", "Alice", "Bob");
List<String> uppercaseNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(uppercaseNames); // Output: [JOHN, ALICE, BOB]
In this example, we create a stream from the list of names and use the map
operation to apply the toUpperCase
function to each name. Finally, we collect the transformed names into a new list.
Reducing a stream means to aggregate its elements into a single value. The reduce
operation combines elements of a stream using a specified binary operator to produce a result.
Consider an example where we want to find the maximum number from a stream of integers:
List<Integer> numbers = Arrays.asList(1, 3, 5, 2, 4);
Optional<Integer> maxNumber = numbers.stream()
.reduce(Integer::max);
maxNumber.ifPresent(System.out::println); // Output: 5
In this example, we use the reduce
operation with the max
binary operator to find the maximum number in the stream of integers. The result is an optional, as the stream might be empty.
Filtering, mapping, and reducing are essential operations when working with streams in Java. They provide a concise and expressive way to manipulate collections of data. By understanding these operations, you can effectively harness the power of streams to streamline your code and make it more readable and maintainable. Happy streaming!
noob to master © copyleft