Skip to content

Tag: java-stream

Get index of element that matches a predicate

I know how to find the first element of a list by predicate: Find first element by predicate Is there an easy way to get the index of that element? Answer If I understood correctly, that’s the classic case where you need IntStream; but that would only apply for a List obviously.

When should I use streams?

I just came across a question when using a List and its stream() method. While I know how to use them, I’m not quite sure about when to use them. For example, I have a list, containing various paths to different locations. Now, I’d like to check whether a single, given path contains any of the pat…

Non-terminal forEach() in a stream?

Sometimes when processing a Java stream() I find myself in need of a non-terminal forEach() to be used to trigger a side effect but without terminating processing. I suspect I could do this with something like .map(item -> f(item)) where the method f performs the side effect and returns the item to the str…

Java 8 modify stream elements

I wanted to write pure function with Java 8 that would take a collection as an argument, apply some change to every object of that collection and return a new collection after the update. I want to follow FP principles so I dont want to update/modify the collection that was passed as an argument. Is there any…

Merge Map<String, List Java 8 Stream

I would like to merge two Map with JAVA 8 Stream: I try to use this implementation: However, this implementation only create a result like: Map<String, List<Object>> If one key is not contained in the mapGlobal, it would be added as a new key with the corresponding List of String. If the key is du…

Does the JDK provide a dummy consumer?

I have a need in a block of code to consume ‘n’ items from a stream then finish, in essence: In my situation, I can’t change the signature to return Stream<T> and simply return stream.skip(n); I have to actually throw away some elements from the stream (not simple logic) – to be …

Conditionally add an operation to a Java 8 stream

I’m wondering if I can add an operation to a stream, based off of some sort of condition set outside of the stream. For example, I want to add a limit operation to the stream if my limit variable is not equal to -1. My code currently looks like this, but I have yet to see other examples of streams