Java.Java8.What final methods for working with streams do you know?

🔹 1. Collecting Results

MethodDescription
collect()Accumulates elements into a collection (like List, Set, Map)
toArray()Converts the stream into an array

Example:

List<String> result = stream.collect(Collectors.toList());

🔹 2. Iterating / Consuming Elements

MethodDescription
forEach()Performs an action for each element (order not guaranteed in parallel)
forEachOrdered()Like forEach, but maintains encounter order

Example:

stream.forEach(System.out::println);

🔹 3. Reducing / Aggregating

MethodDescription
reduce()Combines elements into a single result (e.g., sum, min, max)
count()Returns the number of elements
sum(), average()For numeric streams (IntStream, etc.)
min(), max()Finds the minimum/maximum element

Example:

int total = stream.reduce(0, Integer::sum);

🔹 4. Matching and Searching

MethodDescription
anyMatch()Returns true if any element matches the condition
allMatch()Returns true if all elements match the condition
noneMatch()Returns true if no elements match the condition
findFirst()Returns the first element (optional)
findAny()Returns any element (useful in parallel streams)

Example:

boolean hasNegative = stream.anyMatch(x -> x < 0);

🔹 5. Short-Circuiting

Some terminal methods are also short-circuiting, meaning they don’t need to process the entire stream:

  • findFirst(), findAny()
  • anyMatch(), allMatch(), noneMatch()
  • limit(n) (technically intermediate but works with short-circuiting terminal methods)

🧠 Summary

CategoryMethods
Collectioncollect(), toArray()
IterationforEach(), forEachOrdered()
Reductionreduce(), count(), sum(), min(), max(), average()
MatchinganyMatch(), allMatch(), noneMatch(), findFirst(), findAny()
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.