Can I iterate through a NodeList using for-each in Java?

前端 未结 10 1103
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 00:55

I want to iterate through a NodeList using a for-each loop in Java. I have it working with a for loop and a do-while loop but not for-each.

Node         


        
10条回答
  •  独厮守ぢ
    2020-12-09 01:21

    I know it is late to the party, but...
    Since Java-8 you can write @RayHulha's solution even more concisely by using lambda expression (for creating a new Iterable) and default method (for Iterator.remove):

    public static Iterable iterable(final NodeList nodeList) {
        return () -> new Iterator() {
    
            private int index = 0;
    
            @Override
            public boolean hasNext() {
                return index < nodeList.getLength();
            }
    
            @Override
            public Node next() {
                if (!hasNext())
                    throw new NoSuchElementException();
                return nodeList.item(index++); 
            }
        };
    }
    

    and then use it like this:

    NodeList nodeList = ...;
    for (Node node : iterable(nodeList)) {
        // ....
    }
    

    or equivalently like this:

    NodeList nodeList = ...;
    iterable(nodeList).forEach(node -> {
        // ....
    });
    

提交回复
热议问题