Skip to content
Advertisement

How to iterate over StaxEventItemReader/itemreader?

Currently I want to access the objects inside StaxEventItemReader. This is done by using StaxEventItemReader.read() (xml-file has 50 objects/items), so that I can do something with these objects.

The question is how you can correctly iterate over the items of StaxEventItemReader?

Originally I had something like this:

while (objectStaxEventItemReader.read() != null) {
    invokeRandomMethod(objectStaxEventItemReader.read());
}

The problem is that read() “reads a piece of input data and advance to the next one” (Doc). So at the end only 25 items are processed, since the null checks also advance the “iterator”. So null checks seems to be not possible.

Currently I only have a temporary solution (using for loop):

for (int i = 0; i < 50; i++) {
    invokeRandomMethod(objectStaxEventItemReader.read());
}

All 50 objects are read, but this is not a satisfactory solution since I have to specify that there are 50 elements.

I tried to look around and found the peek method of PeekableItemReader (Doc) which might have been useful, but it is a subinterface of itemreader, so I can’t use it with StaxEventItemReader which just implements itemreader.

Is there a way to check for null or better way to iterate over StaxEventItemReader without having to specify the amount of elements?

Advertisement

Answer

var sentinel = objectStaxEventItemReader.read();

while(sentinel != null) {
    invokeRandomMethod(sentinel);
    sentinel = objectStaxEventItemReader.read();
}

Save your return value in a variable and check if its null.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement