Java basic Iterator iterator

Java basics-using Iterator to traverse a collection

There are three methods in the Iterator class:
Object next() : Returns a reference to the element just passed by the iterator, the return value is Object, which needs to be cast to the type you need

boolean hasNext() : Determine whether there are any accessible elements in the container

void remove() : delete the element just passed by the iterator

The use of iterator is mainly to iterate the object, and then loop out the object properties, let's see how to use it:

public static void main(String[] args) {
    
    
        ArrayList arr = new ArrayList();
        arr.add("AA");
        arr.add("BB");
        arr.add("CC");
        arr.add("DD");
        arr.add("EE");

        //使用方法iterator()要求容器返回一个Iterator
        Iterator i  = arr.iterator();

        //使用hasNext()检查序列中是否还有元素。
        while (i.hasNext()){
    
    
            //使用next()获得序列中的下一个元素。
            String  str = (String) i.next();
            System.out.println(str);
        }
    }

In addition, a new default method was introduced in JDK1.8: forEachRemaining() method, which has the same function as forEach .

public static void main(String[] args) {
    
    
        ArrayList arr = new ArrayList();
        arr.add("AA");
        arr.add("BB");
        arr.add("CC");
        arr.add("DD");
        arr.add("EE");

        //使用方法iterator()要求容器返回一个Iterator
        Iterator i  = arr.iterator();

		i.forEachRemaining(new Consumer() {
    
    
            @Override
            public void accept(Object o) {
    
    
                System.out.println((String)o);
            }
        });
        
        System.out.println("==========================");
        
        //以上写法可以使用lambda表达式简化代码
        //  i.forEachRemaining(String -> System.out.println(String));

        System.out.println("==========================");

        //使用forEach方法遍历集合
        arr.forEach(String -> System.out.println(String));
    }

Can the above method traverse the collection?

Guess you like

Origin blog.csdn.net/weixin_47316336/article/details/109023991