Middle
Tell me about Stream API. Which is faster — Stream API or a for loop?
sobes.tech AI
Answer from AI
Stream API in Java is a convenient way to work with collections and data sequences, allowing you to write declarative code for filtering, transforming, and aggregating elements.
Regarding performance, the for loop is usually faster, especially if it is simple and does not use additional operations. Stream API adds some overhead due to the creation of intermediate objects and lambda expressions.
However, the speed difference is often negligible and only noticeable when processing very large volumes of data or in performance-critical areas.
Example of using Stream API:
List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
List<String> filtered = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
If maximum performance is important, it is better to use a for loop. If readability and convenience are more important, Stream API is preferable.