-1

I'm trying to iterate through the elements in a JsonNode and check if they match some condition. I want to use Streams instead of using the classic iterator. I have code similar to this:

return Stream.generate(jsonNode.fields()::next)
            .allMatch(entry -> {
              switch (entry.getKey()) {
                case "a":
                  return evaluateA(entry.getValue());
                case "b":
                  return evaluateB(entry.getValue());
                default:
                  return false;
              }
            });

But when I run this, I get a java.util.NoSuchElementException. I'm guessing the return statements within the switch case are causing this error. If that is the case, how do I handle this?

drunkenfist
  • 2,958
  • 12
  • 39
  • 73
  • 1
    This has nothing to do with your `switch`. `Stream.generate(jsonNode.fields()::next)` creates an *infinite* stream. There is no check for `hasNext` in your code. Maybe you’re looking for [How to create a Java 8 Stream from an iterator?](https://stackoverflow.com/q/23439780/2711488) – Holger Oct 28 '21 at 09:03
  • `Stream.generate` generates an infinite stream. Surely you don't have an infinite number of fields in your JSON node :) – Sweeper Oct 28 '21 at 09:03
  • You could probably use `takeWhile` and `hasNext` to limit the stream. – MC Emperor Oct 28 '21 at 09:10
  • I suggest that you change your title to something about using iterators with streams, which would make the question a lot more useful. – Sweeper Oct 28 '21 at 09:15
  • Sorry, I'll edit the question and mark as duplicate – drunkenfist Oct 28 '21 at 09:26

1 Answers1

0

You can use gson-utils:

Reader in = null;
Iterator<Book> it = GsonUtils.readListLazy(in, Book.class);
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35