Super concise Java 8 functional (declarative) solution


  • 0
    A

    I am practicing with Java 8 features. As always, using stream is much slower than using a loop, but the code may look cleaner.

    public class Vector2D {
    
    final LinkedList<Iterator> q = new LinkedList<>();
    
    public Vector2D(List<List<Integer>> vec2d) {
        vec2d.stream().forEach(e -> q.offer(e.iterator()));
        initQueue();
    }
    
    private void initQueue() {
        while (q.peek() != null && !q.peek().hasNext()) q.poll();
    }
    
    public int next() {
        int res = (int) q.peek().next();
        initQueue();
        return res;
    }
    
    public boolean hasNext() {
        return !q.isEmpty();
    }
    }

  • 0

    How is

    vec2d.stream().forEach(e -> q.offer(e.iterator()));
    

    "much cleaner and more concise" than

    for (List e : vec2d) q.offer(e.iterator());
    

    ?


  • 0
    A

    You are right, I should rephrase: it may seem cleaner to someone who is into declarative definition. I am not a huge fan of adding .stream() for every collection. I wish Java 8 has introduced stream manipulations directly to collections, i.e.
    vec2d.forEach(e -> q.offer(e.iterator()));
    Then I would argue that it's cleaner.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.