0% found this document useful (0 votes)
0 views25 pages

Stream API Notes

The document is a comprehensive reference guide for the Java Stream API, presented in a tabular format for easy scanning. It covers stream creation methods, intermediate and terminal operations, collectors, and examples of common stream operations. Key features and best practices for using streams, including parallel processing, are also highlighted.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views25 pages

Stream API Notes

The document is a comprehensive reference guide for the Java Stream API, presented in a tabular format for easy scanning. It covers stream creation methods, intermediate and terminal operations, collectors, and examples of common stream operations. Key features and best practices for using streams, including parallel processing, are also highlighted.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

lOMoARcPSD|48577845

The Ultimate Java Stream API Handbook

Data Structures and Algorithm (Birla Institute of Technology and Science, Pilani)

messages.pdf_cover_qr_code_label

messages.studocu_not_sponsored_or_endorsed_by_college
messages.downloaded_by
lOMoARcPSD|48577845

Perfect complete and detailed Java Stream API reference, but


entirely tabular, so it’s concise, easy to scan, and note-ready — like a professional
cheat sheet.

Below is a single, comprehensive tabular version of every part of Stream API,


including creation, intermediate, terminal, collectors, primitive streams, etc.

JAVA STREAM API – COMPLETE TABULAR REFERENCE

1. Stream Creation Methods

Method Description Example

From a
[Link]() [Link]()
Collection

Parallel
[Link]() [Link]()
Stream

[Link](array) From an Array [Link](new int[]{1,2,3})

[Link](T... values) From values [Link]("A","B")

[Link]() Empty Stream [Link]()

Infinite
[Link](Supplier) [Link](Math::random)
Stream

[Link](seed, Infinite
[Link](0, n -> n+1)
UnaryOp) sequence

[Link](seed, hasNext, Finite


[Link](0, n -> n<10, n->n+1)
next) (Java 9+) sequence

Manually
[Link]() Stream.<String>builder().add("A").build()
build stream

Stream of file
[Link](Path) [Link]([Link]("[Link]"))
lines

Merge two
[Link](s1, s2) [Link](a,b)
streams

messages.downloaded_by
lOMoARcPSD|48577845

2. Intermediate Operations (Lazy, Return Stream)

Method Description Example

Filters by
filter(Predicate) filter(x -> x > 10)
condition

Transforms
map(Function) map(String::length)
each element

Maps to
mapToInt(ToIntFunction) mapToInt(String::length)
IntStream

Maps to
mapToLong(ToLongFunction) mapToLong(Long::valueOf)
LongStream

Maps to
mapToDouble(ToDoubleFunction) mapToDouble(Double::valueOf)
DoubleStream

Flattens nested
flatMap(Function) flatMap(List::stream)
streams

flatMapToInt, flatMapToLong, FlatMap to


flatMapToInt(IntStream::of)
flatMapToDouble primitives

Removes
distinct() distinct()
duplicates

Natural order
sorted() sorted()
sort

Custom
sorted(Comparator) sorted([Link]())
comparator

Action on each
peek(Consumer) peek([Link]::println)
(debug)

Limit number
limit(long n) limit(5)
of elements

Skip first n
skip(long n) skip(3)
elements

Take until
takeWhile(Predicate) (Java 9+) takeWhile(x -> x < 10)
predicate fails

messages.downloaded_by
lOMoARcPSD|48577845

Method Description Example

Drop until
dropWhile(Predicate) (Java 9+) dropWhile(x -> x < 10)
predicate fails

3. Terminal Operations (Trigger Execution)

Method Description Return Type / Example

Perform action
forEach(Consumer) void
(unordered)

Preserve encounter
forEachOrdered(Consumer) void
order

toArray() Convert to Object[] Object[]

String[] arr =
toArray(IntFunction<T[]>) Convert to typed array
[Link](String[]::new)

reduce(BinaryOperator) Combine elements Optional<T>

reduce(identity, accumulator) Combine with identity T

reduce(identity, mapper, Map + reduce


U
combiner) (parallel)

collect(Collector) Collect into result Depends on collector

min(Comparator) Smallest element Optional<T>

max(Comparator) Largest element Optional<T>

count() Count elements long

anyMatch(Predicate) True if any match boolean

allMatch(Predicate) True if all match boolean

noneMatch(Predicate) True if none match boolean

findFirst() First element Optional<T>

Any element (parallel-


findAny() Optional<T>
friendly)

messages.downloaded_by
lOMoARcPSD|48577845

4. Short-Circuiting Operations

Category Operations Description

Intermediate limit(), takeWhile() Stop producing stream early

findFirst(), findAny(), anyMatch(), Stop traversal early when


Terminal
allMatch(), noneMatch() condition met

5. Collectors ([Link])

Descripti
Collector Example Output
on

Collect to
toList() .collect([Link]()) List<T>
List

Collect to
toSet() .collect([Link]()) Set<T>
Set

Custom .collect(toCollection(TreeSe Custom


toCollection(Supplier)
collection t::new)) Collection

Key-value .collect(toMap(String::lengt
toMap(kMapper,vMapper) Map<K,V>
map h, s -> s))

Handle
toMap(kMapper,vMapper,m
duplicate .collect(toMap(k,v,(a,b)->a)) Map<K,V>
ergeFn)
s

toMap(k,v,mergeFn,supplie Custom .collect(toMap(k,v,(a,b)->a,


LinkedHashMap
r) map type LinkedHashMap::new))

Group by .collect(groupingBy(String::l
groupingBy(classifier) Map<K,List<V>>
key ength))

Group
groupingBy(classifier, with .collect(groupingBy(String::l
Map<K,Set<V>>
downstream) downstre ength, toSet()))
am

messages.downloaded_by
lOMoARcPSD|48577845

Descripti
Collector Example Output
on

Split into .collect(partitioningBy(x- Map<Boolean,List


partitioningBy(predicate)
true/false >x>5)) <V>>

Partition +
partitioningBy(predicate, .collect(partitioningBy(x- Map<Boolean,Lon
downstre
downstream) >x>5,counting())) g>
am

Count
counting() .collect(counting()) Long
elements

Sum of .collect(summingInt(String::
summingInt(func) Integer
ints length))

Sum of
summingLong(func) .collect(summingLong(...)) Long
longs

Sum of .collect(summingDouble(...)
summingDouble(func) Double
doubles )

Average of
averagingInt(func) .collect(averagingInt(...)) Double
ints

Stats
(count, IntSummaryStatis
summarizingInt(func) .collect(summarizingInt(...))
sum, avg, tics
etc.)

Concaten
joining() ate .collect(joining()) String
strings

Join with
joining(delim) .collect(joining(", ")) "a, b, c"
delimiter

Join +
joining(delim, pre, suf) .collect(joining(", ", "[", "]")) "[a, b, c]"
wrapper

Reduce to .collect(reducing(Integer::su
reducing(BinaryOperator) Optional<T>
one m))

messages.downloaded_by
lOMoARcPSD|48577845

Descripti
Collector Example Output
on

Reduce .collect(reducing(0,
reducing(id, mapper,
with String::length, T
combiner)
mapping Integer::sum))

mapping(mapper, Map + .collect(mapping(String::len


List<Integer>
downstream) collect gth, toList()))

.collect(collectingAndThen(t
collectingAndThen(downstr Post- oList(),
Custom result
eam, finisher) process Collections::unmodifiableLi
st))

6. Custom Collector (Three-Argument collect)

Parameter Role Example

Supplier<R> Creates container ArrayList::new

BiConsumer<R, ? super T> Adds element List::add

BiConsumer<R, R> Merges results List::addAll

List<String> result = [Link](ArrayList::new, List::add, List::addAll);

7. Primitive Streams

Factory
Stream Type Common Ops Example
Methods

range(),
sum(), average(),
rangeClosed(
min(), max(),
IntStream ), of(), [Link](1,10)
summaryStatistics(
iterate(),
), boxed()
generate()

Same as
LongStream sum(), count() [Link](1L,2L)
IntStream

messages.downloaded_by
lOMoARcPSD|48577845

Factory
Stream Type Common Ops Example
Methods

DoubleStrea Same as [Link](Math::rando


average(), sum()
m IntStream m)

8. Stream Static Methods

Method Description Example

[Link](...) Create from elements [Link](1,2,3)

[Link]() Empty stream [Link]()

[Link](...) Infinite / finite sequence [Link](0,n->n+1)

[Link](Supplier) Infinite supply [Link](Math::random)

[Link](s1,s2) Merge streams [Link](a,b)

[Link]() Build manually Stream.<T>builder().add(...).build()

9. Parallel Streams

Operation Description Example

parallelStream() Parallel from Collection [Link]()

Convert existing stream to


parallel() [Link]()
parallel

sequential() Convert back to sequential [Link]()

forEachOrdered() Ensures order in parallel .forEachOrdered([Link]::println)

⚠ Notes:

• Best for large, stateless data.

• Avoid side effects or shared mutable variables.

10. Summary of Stream Operations

messages.downloaded_by
lOMoARcPSD|48577845

Category Methods Returns

filter, map, flatMap, distinct, sorted, peek, limit, skip,


Intermediate Stream
takeWhile, dropWhile

forEach, collect, reduce, count, min, max, anyMatch, Result or side


Terminal
allMatch, noneMatch, findFirst, findAny, toArray effect

Short- limit, takeWhile, findFirst, findAny, anyMatch, allMatch,


Early stop
Circuiting noneMatch

11. Key Stream Features

Feature Description

Non-storage Doesn’t hold data

Functional Doesn’t modify source

Lazy Executes only on terminal op

Parallelizable Supports multi-threading

Single-use Can’t reuse a Stream

Infinite-capable Can handle unbounded streams

12. Common Examples

Purpose Example

Filter + Map [Link]().filter(x->x>10).map(x->x*2).collect(toList())

Grouping [Link]().collect(groupingBy(String::length))

Joining [Link]().collect(joining(", ","[","]"))

Summarizing [Link]().collect(summarizingInt(Integer::intValue))

Reduce [Link]().reduce(0,Integer::sum)

Parallel [Link]().filter(x->x>5).forEach([Link]::println)

messages.downloaded_by
lOMoARcPSD|48577845

1–10: Basic Stream Operations

1. Filter even numbers from a list.


List<Integer> evens = [Link](1,2,3,4,5).stream().filter(n->n%2==0).toList();

2. Square all numbers in a list.


List<Integer> squares = [Link](1,2,3,4,5).stream().map(n->n*n).toList();

3. Convert all strings in a list to uppercase.


[Link]("alice","bob").stream().map(String::toUpperCase).forEach([Link]::println);

4. Filter strings starting with 'a'.


List<String> aNames = [Link]("alice","bob").stream().filter(s->[Link]("a")).toList();

5. Count numbers greater than 3.


long count = [Link](1,2,3,4,5).stream().filter(n->n>3).count();

6. Find the first even number.


Optional<Integer> firstEven = [Link](1,2,3,4).stream().filter(n->n%2==0).findFirst();

7. Find any even number (parallel safe).


Optional<Integer> anyEven = [Link](1,2,3,4).parallelStream().filter(n-
>n%2==0).findAny();

8. Convert list of strings to their lengths.


List<Integer> lengths = [Link]("alice","bob").stream().map(String::length).toList();

9. Filter odd numbers and multiply by 10.


List<Integer> oddTimes10 = [Link](1,2,3,4,5).stream().filter(n->n%2!=0).map(n-
>n*10).toList();

10. Sum all numbers in a list.


int sum = [Link](1,2,3,4,5).stream().mapToInt(Integer::intValue).sum();

11–20: Collectors

11. Collect a stream to a list.


List<Integer> list = [Link](1,2,3,4).stream().collect([Link]());

12. Collect a stream to a set.


Set<Integer> set = [Link](1,2,2,3).stream().collect([Link]());

13. Join strings with comma.


String joined = [Link]("a","b","c").stream().collect([Link](","));

messages.downloaded_by
lOMoARcPSD|48577845

14. Convert list to map (length->string).


Map<Integer,String> map =
[Link]("one","two").stream().collect([Link](String::length, s->s));

15. Partition numbers into even and odd.


Map<Boolean,List<Integer>> partition =
[Link](1,2,3,4).stream().collect([Link](n->n%2==0));

16. Group strings by length.


Map<Integer,List<String>> group =
[Link]("a","aa","b").stream().collect([Link](String::length));

17. Sum all numbers using collector.


long total = [Link](1,2,3).stream().collect([Link](Integer::intValue));

18. Find max number using collector.


Optional<Integer> max = [Link](1,2,3).stream().max(Integer::compareTo);

19. Find min number using collector.


Optional<Integer> min = [Link](1,2,3).stream().min(Integer::compareTo);

20. Find average of numbers.


Double avg = [Link](1,2,3).stream().collect([Link](Integer::intValue));

21–30: Map & Reduce

21. Sum numbers using reduce.


int sumReduce = [Link](1,2,3).stream().reduce(0,Integer::sum);

22. Multiply numbers using reduce.


Optional<Integer> product = [Link](1,2,3,4).stream().reduce((a,b)->a*b);

23. Concatenate strings using reduce.


String concat = [Link]("a","b","c").stream().reduce("",String::concat);

24. Find max using reduce.


Optional<Integer> maxReduce = [Link](1,5,3).stream().reduce(Integer::max);

25. Find min using reduce.


Optional<Integer> minReduce = [Link](1,5,3).stream().reduce(Integer::min);

26. Sum odd numbers using reduce.


int sumOdd = [Link](1,2,3,4).stream().filter(n->n%2!=0).reduce(0,Integer::sum);

27. Double all numbers using map.


List<Integer> doubles = [Link](1,2,3).stream().map(n->n*2).toList();

messages.downloaded_by
lOMoARcPSD|48577845

28. Filter strings longer than 3 chars.


List<String> longStrings = [Link]("a","abcd","xyz").stream().filter(s->[Link]()>3).toList();

29. Convert string list to char list.


List<Character> chars = [Link]("abc","de").stream().flatMap(s->[Link]().mapToObj(c-
>(char)c)).toList();

30. Limit first 3 elements.


List<Integer> first3 = [Link](1,2,3,4,5).stream().limit(3).toList();

Perfect! I will continue with problems 31–80, each followed by a single-line solution,
keeping it concise and interview-ready.

31–40: Sorting & Distinct

31. Remove duplicates from a list.


List<Integer> distinct = [Link](1,2,2,3).stream().distinct().toList();

32. Sort numbers ascending.


List<Integer> sorted = [Link](4,2,3,1).stream().sorted().toList();

33. Sort numbers descending.


List<Integer> descSorted =
[Link](4,2,3,1).stream().sorted([Link]()).toList();

34. Sort strings alphabetically.


List<String> sortedNames = [Link]("bob","alice").stream().sorted().toList();

35. Sort strings by length.


List<String> lengthSorted =
[Link]("bob","alice","a").stream().sorted([Link](String::length)).toList
();

36. Limit stream to first 5 elements.


List<Integer> first5 = [Link](1,2,3,4,5,6).stream().limit(5).toList();

37. Skip first 2 elements.


List<Integer> skip2 = [Link](1,2,3,4,5).stream().skip(2).toList();

38. Find the second largest number.


int secondMax =
[Link](1,3,4,2).stream().sorted([Link]()).skip(1).findFirst().orElse(-1);

39. Find the third smallest number.


int thirdMin = [Link](5,2,3,1,4).stream().sorted().skip(2).findFirst().orElse(-1);

messages.downloaded_by
lOMoARcPSD|48577845

40. Check if all numbers are positive.


boolean allPositive = [Link](1,2,3,4).stream().allMatch(n->n>0);

41–50: AnyMatch, NoneMatch, FindFirst

41. Check if any number is even.


boolean anyEven = [Link](1,3,4).stream().anyMatch(n->n%2==0);

42. Check if no number is negative.


boolean noneNegative = [Link](1,2,3).stream().noneMatch(n->n<0);

43. Find first string starting with 'b'.


Optional<String> firstB = [Link]("alice","bob").stream().filter(s-
>[Link]("b")).findFirst();

44. Find any string starting with 'b'.


Optional<String> anyB = [Link]("alice","bob").parallelStream().filter(s-
>[Link]("b")).findAny();

45. Count distinct numbers.


long distinctCount = [Link](1,2,2,3).stream().distinct().count();

46. Convert array to list using streams.


List<Integer> listFromArray = [Link](new int[]{1,2,3}).boxed().toList();

47. Convert list of integers to comma-separated string.


String csv = [Link](1,2,3).stream().map(String::valueOf).collect([Link](","));

48. Flatten list of lists into single list.


List<Integer> flat = [Link]([Link](1,2),[Link](3,4)).stream().flatMap(List::stream).toList();

49. Find sum of squares of numbers.


int sumSquares = [Link](1,2,3).stream().mapToInt(n->n*n).sum();

50. Multiply all numbers together.


int product = [Link](1,2,3,4).stream().reduce(1,(a,b)->a*b);

51–60: Advanced Filtering & Mapping

51. Filter strings containing 'a'.


List<String> hasA = [Link]("bob","alice","car").stream().filter(s->[Link]("a")).toList();

52. Get lengths of even-length strings.


List<Integer> evenLengths = [Link]("bob","alice","car").stream().filter(s-
>[Link]()%2==0).map(String::length).toList();

messages.downloaded_by
lOMoARcPSD|48577845

53. Convert numbers to string representation.


List<String> stringNumbers = [Link](1,2,3).stream().map(String::valueOf).toList();

54. Get unique characters from a list of strings.


List<Character> uniqueChars = [Link]("ab","bc").stream().flatMap(s-
>[Link]().mapToObj(c->(char)c)).distinct().toList();

55. Filter numbers divisible by 3.


List<Integer> div3 = [Link](1,2,3,4,5,6).stream().filter(n->n%3==0).toList();

56. Convert strings to first character.


List<Character> firstChars = [Link]("bob","alice").stream().map(s->[Link](0)).toList();

57. Filter positive numbers and sum them.


int sumPositive = [Link](-1,2,3,-4).stream().filter(n-
>n>0).mapToInt(Integer::intValue).sum();

58. Find max string length.


int maxLen =
[Link]("bob","alice","car").stream().mapToInt(String::length).max().orElse(0);

59. Find min string length.


int minLen = [Link]("bob","alice","car").stream().mapToInt(String::length).min().orElse(0);

60. Count strings with length > 3.


long countLong = [Link]("bob","alice","car").stream().filter(s->[Link]()>3).count();

61–70: Grouping & Partitioning

61. Group numbers by even/odd.


Map<Boolean,List<Integer>> byEven =
[Link](1,2,3,4).stream().collect([Link](n->n%2==0));

62. Group strings by length.


Map<Integer,List<String>> groupLength =
[Link]("a","aa","bbb").stream().collect([Link](String::length));

63. Count strings by length.


Map<Integer,Long> countByLength =
[Link]("a","aa","bbb").stream().collect([Link](String::length,Collectors.c
ounting()));

64. Sum numbers by even/odd.


Map<Boolean,Integer> sumByEven =
[Link](1,2,3,4).stream().collect([Link](n-
>n%2==0,[Link](Integer::intValue)));

messages.downloaded_by
lOMoARcPSD|48577845

65. Collect numbers into TreeSet.


TreeSet<Integer> treeSet =
[Link](3,1,2).stream().collect([Link](TreeSet::new));

66. Group strings by first character.


Map<Character,List<String>> groupByFirst =
[Link]("apple","banana","avocado").stream().collect([Link](s-
>[Link](0)));

67. Count even and odd numbers.


Map<Boolean,Long> countEvenOdd =
[Link](1,2,3,4).stream().collect([Link](n-
>n%2==0,[Link]()));

68. Group strings by length and map to uppercase.


Map<Integer,List<String>> upperByLength =
[Link]("a","aa","bbb").stream().collect([Link](String::length,Collectors.
mapping(String::toUpperCase,[Link]())));

69. Find max number in each group (even/odd).


Map<Boolean,Optional<Integer>> maxByGroup =
[Link](1,2,3,4).stream().collect([Link](n-
>n%2==0,[Link](Integer::compareTo)));

70. Join strings by first character group.


Map<Character,String> joinByFirst =
[Link]("apple","avocado","banana").stream().collect([Link](s-
>[Link](0),[Link](s->s,[Link](","))));

71–80: Parallel & Optional Operations

71. Parallel stream sum of numbers.


int parallelSum = [Link](1,2,3,4,5).parallelStream().mapToInt(Integer::intValue).sum();

72. Parallel stream max number.


int parallelMax =
[Link](1,2,3,4,5).parallelStream().mapToInt(Integer::intValue).max().orElse(0);

73. Parallel filter even numbers.


List<Integer> parallelEvens = [Link](1,2,3,4,5).parallelStream().filter(n-
>n%2==0).toList();

74. Optional: get value or default.


int value = [Link](5).orElse(0);

messages.downloaded_by
lOMoARcPSD|48577845

75. Optional: map value.


Optional<Integer> mapped = [Link](5).map(n->n*2);

76. Optional: filter value.


Optional<Integer> filtered = [Link](5).filter(n->n>3);

77. Optional: ifPresent action.


[Link](5).ifPresent([Link]::println);

78. Find first even number or default.


int firstEvenOrDefault = [Link](1,3,4).stream().filter(n->n%2==0).findFirst().orElse(-1);

79. Reduce to sum with initial value 10.


int sumInit = [Link](1,2,3).stream().reduce(10,Integer::sum);

80. Reduce to concatenate strings with delimiter.


String concatComma = [Link]("a","b","c").stream().reduce((s1,s2)->s1+","+s2).orElse("");

Perfect! Here’s problems 81–150 with single-line solutions, covering all advanced Java
Stream API concepts you need for interviews.

81–90: FlatMap & Nested Collections

81. Flatten list of arrays into a single list.


List<Integer> flatArray = [Link](new Integer[]{1,2}, new
Integer[]{3,4}).stream().flatMap(Arrays::stream).toList();

82. Flatten nested lists of strings.


List<String> flatStrings = [Link]([Link]("a","b"),
[Link]("c","d")).stream().flatMap(List::stream).toList();

83. Flatten and filter numbers > 2.


List<Integer> filteredFlat = [Link]([Link](1,2),
[Link](3,4)).stream().flatMap(List::stream).filter(n->n>2).toList();

84. Convert nested lists to uppercase strings.


List<String> upperFlat = [Link]([Link]("a","b"),
[Link]("c")).stream().flatMap(List::stream).map(String::toUpperCase).toList();

85. Flatten list of optional integers.


List<Integer> flatOpt = [Link]([Link](1), [Link](2),
[Link]()).stream().flatMap(Optional::stream).toList();

86. Flatten list of strings into list of characters.


List<Character> flatChars = [Link]("ab","cd").stream().flatMap(s->[Link]().mapToObj(c-
>(char)c)).toList();

messages.downloaded_by
lOMoARcPSD|48577845

87. Flatten list and sum values.


int flatSum = [Link]([Link](1,2),
[Link](3,4)).stream().flatMap(List::stream).mapToInt(Integer::intValue).sum();

88. Flatten list and collect distinct values.


List<Integer> distinctFlat = [Link]([Link](1,2),
[Link](2,3)).stream().flatMap(List::stream).distinct().toList();

89. Flatten list and find max value.


int maxFlat = [Link]([Link](1,5),
[Link](2,4)).stream().flatMap(List::stream).mapToInt(Integer::intValue).max().orElse(-1);

90. Flatten list and find min value.


int minFlat = [Link]([Link](1,5),
[Link](2,4)).stream().flatMap(List::stream).mapToInt(Integer::intValue).min().orElse(-1);

91–100: Peek & Debugging

91. Peek elements while collecting.


List<Integer> peeked = [Link](1,2,3).stream().peek([Link]::println).toList();

92. Peek after filter.


List<Integer> peekAfterFilter = [Link](1,2,3).stream().filter(n-
>n%2==1).peek([Link]::println).toList();

93. Peek after map operation.


List<Integer> peekAfterMap = [Link](1,2,3).stream().map(n-
>n*2).peek([Link]::println).toList();

94. Sum using peek to debug values.


int sumPeek =
[Link](1,2,3).stream().peek([Link]::println).mapToInt(Integer::intValue).sum();

95. Count with peek debug.


long countPeek = [Link](1,2,3,4).stream().peek([Link]::println).count();

96. Filter and peek at each step.


List<Integer> filterPeek = [Link](1,2,3,4).stream().filter(n-
>n%2==0).peek([Link]::println).toList();

97. Map and peek for debugging transformed values.


List<Integer> mapPeek = [Link](1,2,3).stream().map(n-
>n*10).peek([Link]::println).toList();

messages.downloaded_by
lOMoARcPSD|48577845

98. Sort and peek elements.


List<Integer> sortPeek =
[Link](3,1,2).stream().sorted().peek([Link]::println).toList();

99. Limit and peek first 2 elements.


List<Integer> limitPeek =
[Link](1,2,3,4).stream().limit(2).peek([Link]::println).toList();

100. Skip and peek remaining elements.


List<Integer> skipPeek =
[Link](1,2,3,4).stream().skip(2).peek([Link]::println).toList();

101–110: Statistics & Summary

101. Get summary statistics of integers.


IntSummaryStatistics stats =
[Link](1,2,3,4).stream().mapToInt(Integer::intValue).summaryStatistics();

102. Get max from summary statistics.


int maxStats =
[Link](1,2,3).stream().mapToInt(Integer::intValue).summaryStatistics().getMax();

103. Get min from summary statistics.


int minStats =
[Link](1,2,3).stream().mapToInt(Integer::intValue).summaryStatistics().getMin();

104. Get sum from summary statistics.


long sumStats =
[Link](1,2,3).stream().mapToInt(Integer::intValue).summaryStatistics().getSum();

105. Get average from summary statistics.


double avgStats =
[Link](1,2,3).stream().mapToInt(Integer::intValue).summaryStatistics().getAverage();

106. Count from summary statistics.


long countStats =
[Link](1,2,3).stream().mapToInt(Integer::intValue).summaryStatistics().getCount();

107. Statistics on even numbers only.


IntSummaryStatistics evenStats = [Link](1,2,3,4).stream().filter(n-
>n%2==0).mapToInt(Integer::intValue).summaryStatistics();

108. Map strings to lengths and get statistics.


IntSummaryStatistics lenStats =
[Link]("a","ab","abc").stream().mapToInt(String::length).summaryStatistics();

messages.downloaded_by
lOMoARcPSD|48577845

109. Filter and sum numbers >2.


int sumGT2 = [Link](1,2,3,4).stream().filter(n->n>2).mapToInt(Integer::intValue).sum();

110. Average numbers divisible by 2.


double avgEven = [Link](1,2,3,4).stream().filter(n-
>n%2==0).mapToInt(Integer::intValue).average().orElse(0);

111–120: Multi-level Grouping & Mapping

111. Group strings by length and first char.


Map<Integer,Map<Character,List<String>>> multiGroup =
[Link]("apple","bat","ant").stream().collect([Link](String::length,Collect
[Link](s->[Link](0))));

112. Group and count occurrences.


Map<Integer,Long> groupCount =
[Link](1,2,2,3).stream().collect([Link](n->n,[Link]()));

113. Group strings by first char and join them.


Map<Character,String> groupJoin =
[Link]("apple","avocado","banana").stream().collect([Link](s-
>[Link](0),[Link](s->s,[Link](","))));

114. Group numbers by mod 3 and sum.


Map<Integer,Integer> modSum =
[Link](1,2,3,4,5,6).stream().collect([Link](n-
>n%3,[Link](Integer::intValue)));

115. Group strings by length and get max string alphabetically.


Map<Integer,Optional<String>> maxStringByLength =
[Link]("a","bb","c").stream().collect([Link](String::length,[Link]
By(String::compareTo)));

116. Partition numbers >3 and <3.


Map<Boolean,List<Integer>> partition3 =
[Link](1,2,3,4,5).stream().collect([Link](n->n>3));

117. Partition strings by length >3.


Map<Boolean,List<String>> partLen =
[Link]("a","abcd","xyz").stream().collect([Link](s->[Link]()>3));

118. Multi-level partition: even/odd and >2/<2.


Map<Boolean,Map<Boolean,List<Integer>>> multiPartition =
[Link](1,2,3,4).stream().collect([Link](n-
>n%2==0,[Link](n->n>2)));

messages.downloaded_by
lOMoARcPSD|48577845

119. Group strings by last char.


Map<Character,List<String>> groupLastChar =
[Link]("apple","angle","bat").stream().collect([Link](s-
>[Link]([Link]()-1)));

120. Group and map to length list.


Map<Character,List<Integer>> groupMapLen =
[Link]("apple","angle","bat").stream().collect([Link](s-
>[Link](0),[Link](String::length,[Link]())));

121–130: Advanced Reduce & Collectors

121. Concatenate strings with delimiter using reduce.


String concatDelim = [Link]("a","b","c").stream().reduce((s1,s2)->s1+"-"+s2).orElse("");

122. Reduce to find longest string.


Optional<String> longest = [Link]("a","abcd","abc").stream().reduce((s1,s2)-
>[Link]()>=[Link]()?s1:s2);

123. Reduce to find shortest string.


Optional<String> shortest = [Link]("a","abcd","abc").stream().reduce((s1,s2)-
>[Link]()<=[Link]()?s1:s2);

124. Reduce numbers to product modulo 10.


int modProd = [Link](2,3,4).stream().reduce(1,(a,b)->(a*b)%10);

125. Reduce with identity and sum squares.


int sumSquaresReduce = [Link](1,2,3).stream().reduce(0,(a,b)->a+b*b);

126. Collect strings to TreeSet (sorted & unique).


TreeSet<String> tree =
[Link]("b","a","a").stream().collect([Link](TreeSet::new));

127. Collect strings to LinkedList.


LinkedList<String> linkedList =
[Link]("a","b").stream().collect([Link](LinkedList::new));

128. Collect numbers into custom set (HashSet).


HashSet<Integer> hashSet =
[Link](1,2,2,3).stream().collect([Link](HashSet::new));

129. Reduce strings to comma-separated.


String commaSep = [Link]("a","b","c").stream().reduce((s1,s2)->s1+","+s2).orElse("");

messages.downloaded_by
lOMoARcPSD|48577845

130. Collect numbers to Map of number->square.


Map<Integer,Integer> numSquare = [Link](1,2,3).stream().collect([Link](n-
>n,n->n*n));

Perfect! I will continue with problems 131–180, each with a single-line solution,
focusing on advanced Java Stream API topics for interview prep.

131–140: Primitive Streams & Ranges

131. Create an IntStream from 1 to 10.


[Link](1,10).forEach([Link]::println);

132. Sum numbers from 1 to 100.


int sum100 = [Link](1,100).sum();

133. Average of numbers from 1 to 10.


double avg10 = [Link](1,10).average().orElse(0);

134. Filter even numbers in range 1–20.


List<Integer> evensRange = [Link](1,20).filter(n-
>n%2==0).boxed().toList();

135. Count numbers divisible by 3 in 1–50.


long countDiv3 = [Link](1,50).filter(n->n%3==0).count();

136. Map numbers 1–5 to their squares.


List<Integer> squaresRange = [Link](1,5).map(n-
>n*n).boxed().toList();

137. Reduce 1–5 to factorial.


int factorial = [Link](1,5).reduce(1,(a,b)->a*b);

138. Sum of odd numbers from 1–20.


int sumOddRange = [Link](1,20).filter(n->n%2!=0).sum();

139. Max number in range 1–100 divisible by 7.


int maxDiv7 = [Link](1,100).filter(n->n%7==0).max().orElse(-1);

140. Min number in range 50–100 divisible by 5.


int minDiv5 = [Link](50,100).filter(n->n%5==0).min().orElse(-1);

141–150: Optional & Streams

messages.downloaded_by
lOMoARcPSD|48577845

141. Optional of even number >2.


Optional<Integer> optEven = [Link](1,2,3,4).stream().filter(n-
>n%2==0&&n>2).findFirst();

142. Optional map to double value.


Optional<Integer> optDouble = [Link](5).map(n->n*2);

143. Optional filter numbers >10.


Optional<Integer> optFilter = [Link](8).filter(n->n>10);

144. Optional ifPresent print.


[Link]("hello").ifPresent([Link]::println);

145. Optional orElse default value.


int valOrDefault = [Link]().orElse(100);

146. Optional orElseGet with supplier.


int valOrGet = [Link]().orElseGet(()->50);

147. Optional orElseThrow exception.


int valOrThrow = [Link](5).orElseThrow();

148. Optional filter and map combined.


Optional<Integer> optCombined = [Link](5).filter(n->n>3).map(n->n*10);

149. Find first number >2 or default.


int firstGT2 = [Link](1,2,3,4).stream().filter(n->n>2).findFirst().orElse(-1);

150. Find max number or default.


int maxOrDefault = [Link](1,5,3).stream().max(Integer::compareTo).orElse(0);

151–160: Advanced Filtering & Mapping

151. Filter strings starting with vowel.


List<String> vowels = [Link]("apple","bat","orange").stream().filter(s-
>"AEIOUaeiou".indexOf([Link](0))>=0).toList();

152. Filter strings ending with 'e'.


List<String> endsE = [Link]("apple","bat","orange").stream().filter(s-
>[Link]("e")).toList();

153. Filter numbers >5 and <15.


List<Integer> rangeNum = [Link](1,6,10,16).stream().filter(n->n>5&&n<15).toList();

154. Map strings to first and last char pair.


List<String> firstLast = [Link]("apple","bat").stream().map(s-
>""+[Link](0)+[Link]([Link]()-1)).toList();

messages.downloaded_by
lOMoARcPSD|48577845

155. Map numbers to negative.


List<Integer> negNumbers = [Link](1,2,3).stream().map(n->-n).toList();

156. Filter even numbers and multiply by 5.


List<Integer> evenTimes5 = [Link](1,2,3,4).stream().filter(n->n%2==0).map(n-
>n*5).toList();

157. Convert list of strings to list of lengths >2.


List<Integer> lenGT2 = [Link]("a","abc","ab").stream().map(String::length).filter(n-
>n>2).toList();

158. Convert numbers to string if even.


List<String> evenStr = [Link](1,2,3,4).stream().filter(n-
>n%2==0).map(String::valueOf).toList();

159. Filter prime numbers from 1–20.


List<Integer> primes = [Link](1,20).filter(n-
>[Link](2,n/2).allMatch(i->n%i!=0)&&n>1).boxed().toList();

160. Map strings to reversed string.


List<String> reversed = [Link]("abc","def").stream().map(s->new
StringBuilder(s).reverse().toString()).toList();

161–170: Combining Streams

161. Combine two lists into one stream.


List<Integer> combined = [Link]([Link](1,2).stream(),
[Link](3,4).stream()).toList();

162. Combine and filter numbers >2.


List<Integer> combinedFilter = [Link]([Link](1,2).stream(),
[Link](3,4).stream()).filter(n->n>2).toList();

163. Combine strings and join.


String combinedStr = [Link]([Link]("a","b").stream(),
[Link]("c").stream()).collect([Link](","));

164. Combine two IntStreams and sum.


int sumCombined = [Link]([Link](1,3),
[Link](4,5)).sum();

165. Combine lists and remove duplicates.


List<Integer> combinedDistinct = [Link]([Link](1,2,2).stream(),
[Link](2,3).stream()).distinct().toList();

messages.downloaded_by
lOMoARcPSD|48577845

166. Combine lists and sort.


List<Integer> combinedSorted = [Link]([Link](3,1).stream(),
[Link](2,4).stream()).sorted().toList();

167. Combine two streams and map to string.


List<String> combinedStrList = [Link]([Link](1,2).stream(),
[Link](3,4).stream()).map(String::valueOf).toList();

168. Combine and count elements.


long combinedCount = [Link]([Link](1,2).stream(),
[Link](3,4).stream()).count();

169. Combine, filter even, map to square.


List<Integer> combinedEvenSquare = [Link]([Link](1,2).stream(),
[Link](3,4).stream()).filter(n->n%2==0).map(n->n*n).toList();

170. Combine, peek, and collect.


List<Integer> combinedPeek = [Link]([Link](1,2).stream(),
[Link](3,4).stream()).peek([Link]::println).toList();

171–180: Edge Cases & Interview-Oriented

171. Stream of Optional and flatten.


List<Integer> flatOptList = [Link]([Link](1), [Link](2),
[Link]()).flatMap(Optional::stream).toList();

172. Stream of nullable elements and filter non-null.


List<String> nonNull = [Link]("a",null,"b").filter(Objects::nonNull).toList();

173. Stream generate random numbers and limit 5.


List<Double> random5 = [Link](Math::random).limit(5).toList();

174. Stream iterate to generate first 5 even numbers.


List<Integer> first5Even = [Link](0,n->n+2).limit(5).toList();

175. Stream of strings, distinct and count.


long distinctCountStr = [Link]("a","b","a").stream().distinct().count();

176. Stream of numbers, skip first 3 and sum remaining.


int skipSum = [Link](1,10).skip(3).sum();

177. Stream of numbers, take while <5.


List<Integer> takeWhileLt5 = [Link](1,10).takeWhile(n-
>n<5).boxed().toList();

messages.downloaded_by
lOMoARcPSD|48577845

178. Stream of numbers, drop while <5.


List<Integer> dropWhileLt5 = [Link](1,10).dropWhile(n-
>n<5).boxed().toList();

179. Stream of strings, sorted by length then alphabetically.


List<String> sortLengthAlpha =
[Link]("aa","b","aaa").stream().sorted([Link](String::length).thenCo
mparing([Link]())).toList();

180. Stream of strings, group by length and find longest string in each group.
Map<Integer,Optional<String>> longestByLen =
[Link]("a","aa","bbb").stream().collect([Link](String::length,Collectors.
maxBy(String::compareTo)));

messages.downloaded_by

You might also like