Use Lambda expressions to traverse Iterator iterator

Java 8 for the introduction of a Iterator forEachRemaining (Consumer action) the default method, parameters required by the method is also a Consumer Function interface. When the program calls the Iterator forEachRemaining (Consumer action) through the collection element, the collection element program sequentially pass the Consumer accept (T t) The method of (abstract only interface method).

java.util.function in Function, Supplier, Consumer, Predicate and other functional interfaces are widely used in support of Lambda expressions API. "Void accept (T t);" Consumer is the core of the method used to define the operations performed for a given parameter T.

Use Lambda expressions to traverse the collection of elements.

public class IteratorEach {
    public static void main(String[] args) {
        // 创建一个集合
        Collection objs = new HashSet();
        objs.add("百度Java教程");
        objs.add("百度C语言教程");
        objs.add("百度C++教程");
        // 获取objs集合对应的迭代器
        Iterator it = objs.iterator();
        // 使用Lambda表达式(目标类型是Comsumer)来遍历集合元素
        it.forEachRemaining(obj -> System.out.println("迭代集合元素:" + obj));
    }
}

The output is:

迭代集合元素:百度C++教程
迭代集合元素:百度C语言教程
迭代集合元素:百度Java教程

In line 11 the above procedure code calls forEachRemaining Iterator () method to traverse the collection element, the method parameter is passed to a Lambda expression, the target type is Consumer Lambda expressions, and therefore the above code can also be used to traverse a set of element.

Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104715988