Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the next element from a spliterator in java

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".

like image 542
jørgen k. s. Avatar asked Sep 06 '19 10:09

jørgen k. s.


2 Answers

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();
        }
    }
like image 92
Felix Avatar answered Oct 03 '22 17:10

Felix


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]
like image 29
Adrian Avatar answered Oct 03 '22 16:10

Adrian