Junior — Middle
What is the difference between peek() and sorted() methods in the context of collections or streams?
sobes.tech AI
Answer from AI
The peek() and sorted() methods in Java Stream API serve different purposes:
-
peek() — intermediate method that allows performing an action on each element of the stream without modifying the stream itself. Usually used for debugging or logging.
-
sorted() — intermediate method that sorts the stream's elements according to natural order or a comparator, returning a new sorted stream.
Example:
List<String> list = Arrays.asList("banana", "apple", "cherry");
list.stream()
.peek(s -> System.out.println("Before sorting: " + s))
.sorted()
.peek(s -> System.out.println("After sorting: " + s))
.collect(Collectors.toList());
In this example, peek() outputs elements before and after sorting, while sorted() changes the order.
Summary:
peek()— for side effects without data modification.sorted()— for changing the order of stream elements.