Java Stream API

The Stream API in Java is used for functional-style operations on collections of data. It was introduced in Java 8 and provides a powerful way to process sequences of elements.

Key Features of Stream API

Declarative – Focuses on what to do, not how to do it.

Lazy Evaluation – Operations are performed only when necessary.

Functional Programming – Uses lambda expressions and method references.

Parallel Processing – Improves performance on large data sets.

Non-Mutable – Does not modify the original collection.

Creating Streams:

import java.util.List;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("Alice", "Bob", "Charlie");
// Creating a stream
Stream<String> nameStream = names.stream();
nameStream.forEach((item)->{
System.out.println("item -> "+item);
});
}
}

Stream Operations:

There are two types of operations in Stream API:

  1. Intermediate Operations – Return another Stream (e.g., filter(), map(), sorted()).
  2. Terminal Operations – Produce a result (e.g., forEach(), collect(), reduce()).


Method

Description

Filters elements based on a condition.

Collects results into a list.

Transforms elements.

Sorts elements.

Counts elements in the stream.

Combines all elements into one.

Checks conditions on elements.

Filtering Elements (filter()) and Collecting Elements (collect():

  • Filters elements based on a condition.
  • Converts the Stream into a List, Set, or Map.
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = List.of(10, 15, 20, 25, 30);
// Filter even numbers
List<Integer> evenNumbers = numbers.stream()
.filter((n) -> {
if(n % 2 == 0){
return true;
}else{
return false;
}
}).collect(Collectors.toList());
System.out.println(evenNumbers);
}
}

Transforming Elements (map()):

Modifies each element in the stream.

import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> names = List.of("Alice", "Bob", "Charlie");
// Convert names to uppercase
List<String> upperCaseNames = names.stream()
.map((item)->{
return item.toUpperCase();
})
.collect(Collectors.toList());
System.out.println(upperCaseNames);
}
}

Sorting Elements (sorted()):

Sorts elements in natural order or custom order.

import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("Charlie", "Alice", "Bob");
// Sort names
names.stream().sorted().forEach((item)->{
System.out.println(item);
});
}
}

Counting Elements (count()):

Counts the number of elements in the stream.

import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> names = List.of("Alice", "Bob", "Charlie");

// Count elements
long count = names.stream().count();
System.out.println("Total count: " + count);
}
}

Reducing Elements (reduce()):

Combines all elements into a single value.

import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);

// Sum all numbers
int sum = numbers.stream()
.reduce(0, (item,acc)->{
acc += item;
return acc;
});
System.out.println("Sum: " + sum);
}
}

Checking Conditions (anyMatch(), allMatch()):

import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = List.of(10, 20, 30, 40, 50);

// Check if any number is greater than 25
boolean anyGreaterThan25 = numbers.stream().anyMatch(n -> n > 25);
boolean allGreaterThan25 = numbers.stream().allMatch(n -> n > 25);
System.out.println("Any number > 25: " + anyGreaterThan25);
System.out.println("All number > 25: " + allGreaterThan25);
}
}

Parallel Streams for Performance:

Java provides parallel streams for multi-threaded processing.

import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);

// Using parallel stream
numbers.parallelStream().forEach(item-> System.out.println(item));
}
}

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.