What does the peek() method do?
sobes.tech AI
Answer from AI
The peek() method in Java is used to retrieve elements from various collections without removing them. Its behavior depends on the interface or class in which it is defined.
In the context of Java SE, peek() is typically used:
-
In the
Dequeinterface (and its implementations such asArrayDeque,LinkedList): Returns the top (first) element of the deque, but does not remove it. If the deque is empty, it returnsnull.// Example of using peek() for Deque import java.util.Deque; import java.util.ArrayDeque; public class DequePeekExample { public static void main(String[] args) { Deque<String> deque = new ArrayDeque<>(); deque.offerLast("Element 1"); deque.offerLast("Element 2"); String firstElement = deque.peek(); // Returns "Element 1" without removing it System.out.println("First element: " + firstElement); // Output: First element: Element 1 System.out.println("Deque after peek: " + deque); // Output: Deque after peek: [Element 1, Element 2] } } -
In the
Queueinterface (and its implementations such asLinkedList,PriorityQueue): Returns the head (first) element of the queue, but does not remove it. If the queue is empty, it returnsnull.// Example of using peek() for Queue import java.util.Queue; import java.util.LinkedList; public class QueuePeekExample { public static void main(String[] args) { Queue<Integer> queue = new LinkedList<>(); queue.offer(10); queue.offer(20); Integer headElement = queue.peek(); // Returns 10 without removing it System.out.println("Head element: " + headElement); // Output: Head element: 10 System.out.println("Queue after peek: " + queue); // Output: Queue after peek: [10, 20] } } -
In streams with the intermediate
peek()operation: Performs an action on each element of the stream without affecting its contents. Mainly used for debugging or logging, allowing to "peek" at elements as they pass through the pipeline.// Example of using peek() in Streams import java.util.stream.Stream; public class StreamPeekExample { public static void main(String[] args) { Stream.of("a", "b", "c") .peek(s -> System.out.println("Processing: " + s)) // Performs action for each element .map(String::toUpperCase) .forEach(System.out::println); } }
Main characteristics of peek():
- Does not modify the collection/stream: Unlike methods like
poll()orremove(),peek()only views the element. - Returns
null: For collections, if they are empty,peek()returnsnull(unlikeelement(), which throws aNoSuchElementException). - Lazy in Streams: In streams, the
peek()operation is intermediate and only executes when the terminal operation of the stream pipeline is invoked.
Thus, peek() provides a safe way to check the next available element without removing it.