PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 19, 2022

[FIXED] How to return the next element from a spliterator in java

 September 19, 2022     consumer, iterator, java, java-8, spliterator     No comments   

Issue

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


Solution

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();
        }
    }


Answered By - Felix
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing