5

I want to get the next element from a spliterator, not just "perform action" on the next element. For example by implementing the following method

<T> T getnext(Spliterator<T> s) {

}

All search results I found just said that tryAdvance() was like a combination of an iterators hasNext() and next(), except that is a BIG LIE because I can't get next element, just "perform action on next element".

3 Answers 3

4

You can wrap the item in a list and then return from that list:

    public static <T> T getNext(Spliterator<T> spliterator) {
        List<T> result = new ArrayList<>(1);

        if (spliterator.tryAdvance(result::add)) {
            return result.get(0);
        } else {
            return null;
        }
    }

To make it more obvious to the caller that this is an operation that may return null, consider returning Optional:

    public static <T> Optional<T> getNext(Spliterator<T> spliterator) {
        final List<T> result = new ArrayList<>(1);

        if (spliterator.tryAdvance(result::add)) {
            return Optional.of(result.get(0));
        } else {
            return Optional.empty();
        }
    }
1
  • 2
    If you want to return an Optional, this answer is simpler. Your first variant can be simplified to return spliterator.tryAdvance(result::add)? result.get(0): null; Or you use Deque<T> d = new ArrayDeque<>(1); spliterator.tryAdvance(d::push); return d.poll(); instead.
    – Holger
    Sep 6, 2019 at 12:07
1

transform spliterator to stream

<T> Optional<T> getnext(Spliterator<T> s) {
    return StreamSupport.stream(s, false).findFirst();
}

example

List<String> lst = List.of("a", "b");
Spliterator<String> spliterator = lst.spliterator();

System.out.println(getnext(spliterator)); //Optional[a]
System.out.println(getnext(spliterator)); //Optional[b]
1

There are no direct way but you can use :

<T> T getnext(Spliterator<T> s) {
    Stream<T> stream = StreamSupport.stream(s, false); // convert Spliterator to stream
    Iterable<T> iterable = stream::iterator; // then stream to Iterable
    return iterable.iterator().next(); // then you can get next element
 }

Or in one step like so :

 return StreamSupport.stream(s, false).iterator().next();

Or more simpler :

 return Spliterators.iterator(s).next();
4
  • It doesn't look like the right approach: too many steps (spliterator -> stream -> iterator) Sep 6, 2019 at 10:44
  • and it could be simplified to return StreamSupport.stream(s, false).iterator().next(); Sep 6, 2019 at 10:45
  • @Andrew I agree but there are no direct way Sep 6, 2019 at 10:48
  • 2
    Even simpler with return Spliterators.iterator(s).next()
    – Holger
    Sep 6, 2019 at 12:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.