Java 8
Java 8
**Introduction to Streams:**
- **Definition:** A Stream is a sequence of elements supporting sequential and
parallel aggregate operations.
- **Key Characteristics:**
- **Functional Programming:** Streams enable functional-style programming.
- **Pipelining:** Operations can be pipelined to form a sequence of
transformations.
- **Immutable:** Streams do not modify the underlying data source.
- **Laziness:** Operations are performed only when needed.
- **Creating Streams:**
- From a Collection: `List.stream()`, `Set.stream()`, `Map.entrySet().stream()`.
- From an Array: `Arrays.stream(array)`.
### 4. **FlatMap:**
- **Definition:** `flatMap` is used to flatten a stream of collections into a single
stream.
- **Example:**
```java
List<List<Integer>> listOfLists = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3,
4));
List<Integer> flatList = listOfLists.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
```
### 5. **Sorting:**
- Use `sorted` to order the elements of a stream.
- Example: `stream.sorted()`, `stream.sorted(Comparator.reverseOrder())`.
### 6. **Reducing:**
- **Definition:** The `reduce` operation performs a reduction on the elements
of the stream.
- **Example:**
```java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
```
### 7. **Collectors:**
- **Definition:** The `Collectors` utility class provides various predefined
collectors for common use cases.
- **Examples:**
```java
List<String> list = stream.collect(Collectors.toList());
Set<String> set = stream.collect(Collectors.toSet());
String result = stream.collect(Collectors.joining(", "));
```
These notes cover the fundamental concepts and operations of Java 8 Streams.
They provide a foundation for leveraging the powerful capabilities of the Streams
API to write cleaner, more expressive, and often more efficient code when
working with collections in Java.