Java Stream API Operations
Java Stream API Operations
Terminal Operations
INTERMEDIATE OPERATIONS
filter()
• When to Use: To remove unwanted elements based on a condition.
• Example:
map()
• When to Use: To transform each element, like converting or formatting.
• Example:
sorted()
• When to Use: To sort the stream elements.
• Example:
distinct()
• When to Use: To remove duplicates.
• Example:
List<Integer> nums = List.of(1, 2, 2, 3);
nums.stream()
.distinct()
.forEach(System.out::println); // Output: 1 2 3
limit(n)
• When to Use: To limit to the first n elements.
• Example:
skip(n)
• When to Use: To skip the first n elements.
• Example:
flatMap()
• When to Use: To flatten nested collections.
• Example:
forEach()
• When to Use: To perform an action for each element.
• Example:
count()
• When to Use: To count the number of elements.
• Example:
reduce()
• When to Use: To combine elements into one result.
• Example:
allMatch()
• When to Use: To check if all elements match the condition.
• Example:
noneMatch()
• When to Use: To check if none of the elements match the condition.
• Example:
findFirst()
• When to Use: To get the first element.
• Example:
findAny()
• When to Use: To get any one element (useful in parallel streams).
• Example:
Optional<String> any = List.of("One", "Two")
.stream()
.findAny();
System.out.println(any.get()); // Output: One (or any one)