Where is the tee in the Java Stream API?

Where is the tee in the Java Stream API?

I seem to remember seeing a tee somewhere in Java stream, which allows to extract the elements in the running stream and, for example, log them. But I can't find it anymore. Of course, that's possible:

var result = collection.stream().filter(predicate1).map(obj -> {
    System.out.println(obj);
    return obj;
}).filter(predicate2).collect(Collectors.toList());

But what I was looking for was something like this, a shortcut for it:

var result = collection.stream().filter(predicate1).tee(System.out::println)
        .filter(predicate2).collect(Collectors.toList());

I'm not talking about the teeing collector, which was introduced with Java 12, but something that existed before.

Answer

While writing my question, I found the T-piece again, and here it is: It's called peek.

var result = collection.stream().filter(predicate1).peek(System.out::println)
        .filter(predicate2).collect(Collectors.toList());

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles