Sobes.tech
Junior — Middle

What is the purpose of the peek() method in collections or data streams?

sobes.tech AI

Answer from AI

The peek() method in collections or data streams allows you to look at the next element without removing it from the data structure. This is useful when you want to see what will be next, but still preserve the state of the collection or stream.

For example, in a queue, peek() returns the element that will be retrieved next, but does not remove it from the queue.

Example in Java using Queue:

Queue<String> queue = new LinkedList<>();
queue.add("First");
queue.add("Second");

String next = queue.peek(); // returns "First", but the element remains in the queue
System.out.println(next); // output: First

String polled = queue.poll(); // retrieves and removes "First"
System.out.println(polled); // output: First

Thus, peek() allows you to safely look at the next element without modifying the collection.

What is the purpose of the peek() method in… - sobes.tech