Sobes.tech
Junior — Middle

Can you explain what the function of the peek method is in the context of working with collections or data structures?

sobes.tech AI

Answer from AI

The peek method in the context of collections or data structures usually allows you to look at (view) the element at the top of the structure (for example, a stack or queue) without removing that element from the structure.

For example, in a stack, peek returns the top element but does not modify the stack:

Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
int top = stack.peek(); // top = 20, stack remains unchanged

This is useful when you need to know which element will be processed next, while keeping the data structure unchanged.