Sunday, February 5, 2023

Java 8 Stream API

 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.


  1. 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.
  1. 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


  1. 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

  1. 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

  1. 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

Concurrent Hashmap in java

  A ConcurrentHashMap is a thread-safe implementation of the Map interface in Java. Unlike a HashMap , which is not thread-safe and can ca...