One of the workarounds for using the Stream
would be to keep track of last index of text
s from Bean
.
Map<String, Integer> lastIndexMap = IntStream.range(0, list.size())
.boxed()
.collect(Collectors.toMap(a -> list.get(a).getText(), a -> a, Integer::max));
This way you can easily then access the next element after certain text's last index.
Bean afterLastIndexOfNull = list.get(lastIndexMap.get(null) + 1);
The drawback especially in your case if the null
text value which I am turning into the null
keys in the Map
. They should be highly discouraged and for that reason you can choose to implement a wrapper to convert null
to some default text and then lookup based on the same as well.
Gotchas
One of the gotchas with the above approach is that you could get an array index out of bounds exception while trying to access
list.get(lastIndexMap.get(<key>) + 1)
and the key text is also present in the last element of the list.
Another point as Holger has also mentioned in the comments explicitly is that this approach prepares a lot of information.
Note there is a trade-off in terms of what your queries further might be. If you want to prepare for lookups of list of texts. This approach might be useful for a single iteration and faster access.
But on the other hand, if it's just a one-time computation then its worth minimizing the information to just the single index. Holger has already suggested a solution to that as well.
OptionalInt lastIndex = IntStream.range(0, list.size())
.filter(ix -> list.get(ix).getText() == null)
.reduce((a, b) -> b);