Stream in Java ?

 In Java, the Stream API, introduced in Java 8, is a powerful and flexible way to process sequences of elements. It provides a high-level abstraction for operations on collections of data. A stream is not a data structure; instead, it takes input from collections, arrays, or I/O channels. Streams can be used to perform operations like filtering, mapping, and reducing on collections of data in a more declarative and functional style.


### Key Features of Streams


1. **Declarative**: Streams allow you to write code that describes what you want to achieve, rather than how to achieve it.

2. **Composability**: Streams support operations that can be combined to form complex data processing pipelines.

3. **Parallelism**: Streams can be processed in parallel, making it easier to leverage multi-core processors.

4. **Laziness**: Streams are lazy and do not perform any computations until they are explicitly needed. This allows for more efficient processing.


### Stream Operations


Stream operations are divided into two categories:


1. **Intermediate Operations**: These operations return a new stream and are lazy. They are only performed when a terminal operation is invoked.

   - Examples: `filter`, `map`, `flatMap`, `distinct`, `sorted`, `limit`, `skip`

2. **Terminal Operations**: These operations produce a result or a side effect and are not lazy. They trigger the processing of the stream.

   - Examples: `forEach`, `collect`, `reduce`, `count`, `findFirst`, `findAny`, `allMatch`, `noneMatch`, `anyMatch`


### Creating Streams


You can create streams from various sources, such as collections, arrays, or I/O channels.


- From a collection:

  ```java

  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

  Stream<Integer> numberStream = numbers.stream();

  ```


- From an array:

  ```java

  String[] names = {"Alice", "Bob", "Charlie"};

  Stream<String> nameStream = Arrays.stream(names);

  ```


- Using Stream builders:

  ```java

  Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);

  ```


### Example Usage of Streams


Here are some examples of how to use the Stream API:


#### Example 1: Filtering and Printing


```java

import java.util.Arrays;

import java.util.List;

import java.util.stream.Stream;


public class Main {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);


        // Create a stream from the list

        Stream<Integer> numberStream = numbers.stream();


        // Filter the stream to include only even numbers and print them

        numberStream.filter(n -> n % 2 == 0)

                    .forEach(System.out::println);

    }

}

```


Output:

```

2

4

6

8

10

```


#### Example 2: Mapping and Collecting


```java

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;


public class Main {

    public static void main(String[] args) {

        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");


        // Create a stream from the list

        List<String> upperCaseNames = names.stream()

                                           .map(String::toUpperCase)

                                           .collect(Collectors.toList());


        System.out.println(upperCaseNames);

    }

}

```


Output:

```

[ALICE, BOB, CHARLIE]

```


#### Example 3: Reducing


```java

import java.util.Arrays;

import java.util.List;


public class Main {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);


        // Create a stream from the list

        int sum = numbers.stream()

                         .reduce(0, Integer::sum);


        System.out.println("Sum: " + sum);

    }

}

```


Output:

```

Sum: 15

```


### Summary


- **Streams** are a powerful feature in Java for processing sequences of elements in a functional style.

- **Intermediate operations** (like `filter`, `map`) return a new stream and are lazy.

- **Terminal operations** (like `forEach`, `collect`) produce a result or side effect and trigger the processing of the stream.

- **Streams** can be created from collections, arrays, and other data sources.

- **Streams** support parallel processing, making them efficient for large data sets.


By leveraging streams, you can write more concise and readable code that is easy to parallelize and efficient in processing large amounts of data.

Comments

Popular posts from this blog

Collection Framework of Java

What is DBMS ?

Compiler vs Interpreter vs JIT Compiler