Java Stream API Cheat Sheet
1. Stream Creation
Arrays.stream(arr) // From array
list.stream() // From List
Stream.of(1, 2, 3) // Direct values
IntStream.range(1, 5) // 1 to 4
2. Intermediate Operations (Transforming Data)
filter() - Keep elements that match condition ex: .filter(n -> n % 2 == 0)
map() - Convert each element ex: .map(n -> n * 2)
sorted() - Sort elements ex: .sorted()
distinct() - Remove duplicates ex: .distinct()
limit(n) - Keep only first n elements ex: .limit(3)
skip(n) - Skip first n elements ex: .skip(2)
peek() - Inspect stream steps ex: .peek(System.out::println)
3. Terminal Operations (Get Results)
collect() - Gather into List, Set, Map ex: .collect(Collectors.toList())
forEach() - Perform action on each element ex: .forEach(System.out::println)
count() - Number of elements ex: .count()
toArray() - Convert to array ex: .toArray()
reduce() - Accumulate into a single result ex: .reduce(0, Integer::sum)
anyMatch() - True if any match condition ex: .anyMatch(n -> n > 10)
allMatch() - True if all match condition ex: .allMatch(n -> n > 0)
noneMatch() - True if none match condition ex: .noneMatch(n -> n < 0)
findFirst() - Get the first element (Optional) ex: .findFirst()
4. Collectors (for collect())
Collectors.toList() - Convert to List
Collectors.toSet() - Convert to Set
Collectors.joining(", ") - Join strings with separator
Collectors.groupingBy() - Group by key
Collectors.toMap() - Convert to map
Collectors.counting() - Count elements
Collectors.summingInt() - Sum of integers
5. Example: All-in-One
List<Integer> result = list.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.sorted()
.collect(Collectors.toList());
Tip: Use stream().peek() for debugging intermediate steps!