Peek method of Stream class

  • Java program to use peek() API to debug the Stream operations and logging Stream elements as they are processed.
  • Stream.peek() without any terminal operation does nothing
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
 
list.stream()
    .peek( System.out::println );       //prints nothing

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
         
List<Integer> newList = list.stream()
            .peek(System.out::println)
            .collect(Collectors.toList());
 
System.out.println(newList);

Leave a Comment