Java 8 Stream API is a part of the Java SE 8 release that provides a functional-style programming approach to processing collections of data. It allows developers to process collections in a more concise, readable, and efficient manner.
Streams can be thought of as pipelines through which data flows. They provide a way to process data in parallel, thus making the processing faster.
- Filter: The filter operation is used to filter elements in a stream based on a specified condition
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
numbers.stream().filter(n -> n % 2 == 0).forEach(System.out::println);
Output:
2 4 6 8 10
2.
- Map: The map operation is used to transform elements in a stream by applying a function to each element.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); numbers.stream().map(n -> n * n).forEach(System.out::println);
Output:
1
4
9
16
25
- FlatMap: The flatMap operation is used to transform elements in a stream into multiple other elements.
List<List<Integer>> lists = Arrays.asList( Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6), Arrays.asList(7, 8, 9) ); lists.stream().flatMap(list -> list.stream()).forEach(System.out::println);
Output:
1
2
3
4
5
6
7
8
9
- Reduce: The reduce operation is used to reduce the elements in a stream to a single value by applying a binary operator.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
System.out.println(sum);
Output:
15
- Collect: The collect operation is used to collect elements from a stream into a collection.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squaredNumbers = numbers.stream().map(n -> n * n).collect(Collectors.toList());
squaredNumbers.forEach(System.out::println);
Output:
1
4
9
16
25
No comments:
Post a Comment