Can Java 8 streams consume multiple items from the mapping pipeline
I have some data stored in a JPA repository that I am trying to process. I would like to use Java 8 Streams for this but cannot figure out how to get the information I need. This particular "Entity" is actually only for recovery, so it contains items to be processed after something like a power failure / restart.
Using pre-Java 8 for loops would look like this:
List<MyEntity> deletes = myEntityJpaRepository.findByDeletes();
for (MyEntity item : deletes) {
String itemJson = item.getData();
// use a Jackson 'objectMapper' already setup to de-serialize
MyEventClass deleteEvent = objectMapper.readValue(itemJson, MyEventClass.class);
processDelete(deleteEvent, item.getId());
}
The problem comes from the parameters method, which is called at the very end. Using Streams, I believe I would do:
// deletes.stream()
// .map(i -> i.getData())
// .map(event -> objectMapper.readValue(event, MyEventClass.class))
// .forEach(??? can't get 'id' here to invoke 2 parameter method);
I have a solution (no Streams) that I can live with. However, I think this problem comes up a lot, so my question is: In general, is there a way to use Streams to accomplish what I am trying to do?
source to share
Why Pair
not go back to your map
operation:
.map(i -> new Pair<>(i.getData(), i.getId()))
.map(pair -> new Pair<>(objectMapper.readValue(pair.getLeft(), MyEventClass.class), pair.getRight())
.forEach(p -> processDelete(pair.getLeft(), pair.getRight()))
I haven't compiled this, so there may be small things that need to be fixed. But in general you will need Holder
to pass your objects to the next stage in such a case. Either a Pair
, or some type, or even array
.
source to share
This is at least a start, I think it depends on why you want to use a stream and how much you want to make it more functional.
List<MyEntity> deletes = myEntityJpaRepository.findByDeletes();
deletes.stream().foreach(item -> {
String itemJson = item.getData();
// use a Jackson 'objectMapper' already setup to de-serialize
MyEventClass deleteEvent = objectMapper.readValue(itemJson, MyEventClass.class);
processDelete(deleteEvent, item.getId());
});
source to share