Java 8 Stream API Terminal Operations: count, findFirst, anyMatch

🚀 15 Days of Java 8 – #Day8: Other Terminal Operations Besides `collect()`, what are some other common terminal operations in the Stream API? ✅ Answer: While `collect()` is very flexible, there are other simpler terminal operations for specific tasks: - `forEach(action)`: Performs an action for each element of the stream. (e.g., printing each element). - `count()`: Returns the number of elements in the stream as a `long`. - `findFirst()` / `findAny()`: Returns an `Optional` describing the first element of the stream, or any element for parallel streams. - `anyMatch(predicate)` / `allMatch(predicate)`: Returns a `boolean` indicating if any/all elements match a given predicate. //--- Code Snippet --- List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // Count names starting with 'A' long count = names.stream().filter(s -> s.startsWith("A")).count(); // 1 // Check if any name has more than 5 characters boolean anyLongNames = names.stream().anyMatch(s -> s.length() > 5); // true //-------------------- 💡 Takeaway: Choose the simplest terminal operation that fits your needs. If you just need a count or a boolean check, `count()` or `anyMatch()` are much more direct than using `collect()`. 📢 Many of these operations help avoid writing complex loops and stateful variables. 🚀 Day 9: Let's do a coding challenge! 💬 What is the difference between `findFirst()` and `findAny()`? 👇 #Java #Java8 #StreamAPI #CoreJava #InterviewPrep #15DaysOfJava8

To view or add a comment, sign in

Explore content categories