Java 8 streams can use multiple projects in a mapping pipeline

I have some data stored in the JPA repository I'm trying to process I wish I could use Java 8 streams to do this, but I can't figure out how to get the required information This specific "entity" is actually only used for recovery, so it contains items that need to be processed after power failure / restart

Using the pre Java 8 for loop, the code looks like:

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 arises from the two parameter method of the last call. With streams, I believe I will:

//      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 tolerable solution (no streams) But I think there are a lot of problems, so my question is: in general, is there a way to use streams to accomplish what I want to do?

Solution

Why not return a pair on a 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 didn't compile it, so I may need to fix some small problems But in general, in this case, you need a holder to pass your object to the next stage A pair or a type or even an array

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>