peek() method in a stream pipeline is used to perform a certain action on each element of the stream, without modifying the elements themselves. It allows for debugging or other side-effects to be performed on the stream elements, while the stream itself remains unchanged.

Peek method Examples:

List<Person> people = Arrays.asList(new Person("Jayaram", 25), new Person("Ram", 30), new Person("Vijay", 35));
people.stream()
    .filter(p -> p.getAge() >= 30)
    .peek(p -> System.out.println("Filtered person: " + p.getName()))
    .sorted(Comparator.comparing(Person::getName))
    .peek(p -> System.out.println("Sorted person: " + p.getName()))
    .forEach(p -> System.out.println("Final person: " + p.getName()));

In this example, we have a list of people and we are creating a stream from it. Then we are applying filter to keep people who are 30 years old or older, then we are applying peek method to print the filtered people. Then we are applying sorted to sort the filtered people by name, and again applying peek method to print the sorted filtered people. Finally, we are applying forEach to print the final result.

As you can see, the peek() method allows you to perform a certain action on each element of the stream while the stream itself remains unchanged, it’s useful for debugging or other side-effects on the stream elements.

Peek method sample code 2:

List<String> words = Arrays.asList("cat", "dog", "tiger", "horse");
words.stream()
    .filter(s -> s.length() > 5)
    .peek(s -> System.out.println("Filtered word: " + s))
    .map(String::toUpperCase)
    .peek(s -> System.out.println("Uppercase word: " + s))
    .forEach(s -> System.out.println("Final word: " + s));

In this example, we have a list of words and we are creating a stream from it. Then we are applying filter to keep words with more than 5 letters, then we are applying peek method to print the filtered words. Then we are applying map to uppercase the filtered words and again applying peek method to print the uppercase filtered words. Finally, we are applying forEach to print the final result.

Peek method Example code 3:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

numbers.stream()
    .filter(n -> n % 2 == 0)
    .peek(n -> System.out.println("Filtered number: " + n))
    .map(n -> n * n)
    .peek(n -> System.out.println("Squared number: " + n))
    .forEach(n -> System.out.println("Final number: " + n));

In this example, we have a list of numbers and we are creating a stream from it. Then we are applying filter to keep only even numbers, then we are applying peek method to print the even numbers. Then we are applying map to square the even numbers and again applying peek method to print the squared even numbers. Finally, we are applying forEach to print the final result.