Java 集合List及Map中forEach方法

时间:2025-02-16 11:06:58

我们先看一个forEach()方法遍历List集合的例子:

        //使用包创建集合
        List<String> list =("a","b","c","d");

        //遍历1  其中anyThing可以用其它字符替换
        ((anyThing)->(anyThing));
        //遍历2
        (any->(any));
        //匹配输出 : "b"
        (item->{
            if("b".equals(item)){
                (item);
            }
        });

我们看一下forEach()的实现:

public interface Iterable<T> {

    Iterator<T> iterator();

    default void forEach(Consumer<? super T> action) {
        (action);
        for (T t : this) {
            (t);
        }
    }

    default Spliterator<T> spliterator() {
        return (iterator(), 0);
    }
}

可以看到:forEach()方法是Iterable<T>接口中的一个方法。Java容器中,所有的Collection子类(List、Set)会实现Iteratable接口以实现foreach功能。forEach()方法里面有个Consumer类型,它是Java8新增的一个消费型函数式接口,其中的accept(T t)方法代表了接受一个输入参数并且无返回的操作。

@FunctionalInterface
public interface Consumer<T> {
    /* 接收单个参数,返回为空 */
    void accept(T t);

    default Consumer<T> andThen(Consumer<? super T> after) {
        (after);
        return (T t) -> { accept(t); (t); };
    }
}

我们可以这样使用Consumer接口

public class Test {
    //自定义一个test方法
    public static void test(int value, Consumer<Integer> consumer) {
        (value);
    }
    public static void main(String[] args) {

        //这里,Consumer消费型函数式接口代表了接受一个输入参数并且无返回的操作
        //(x) -> (x * 2)代表接受一个输入参数x,这里 x=3
        //可以使用lambda表达式,输出结果为6
        test(3, (x) -> (x * 2));
    }
}

forEach()方法同样可以遍历存储其它对象的List集合:

        List<User> list =(new User("aa",10),
                                                      new User("bb",11),
                                                      new User("cc",12));
        //遍历  其中any可以用其它字符替换
       // (any->(any));
        //匹配输出,匹配项可以为list集合元素的属性(成员变量)
        (any->{
            if(new User("bb",11).equals(any)){
                (any);
            }
        });
    }

map集合不属于Collection,它有自己的foreach()方法:

    default void forEach(BiConsumer<? super K, ? super V> action) {
        (action);
        for (<K, V> entry : entrySet()) {
            K k;
            V v;
            try {
                k = ();
                v = ();
            } catch(IllegalStateException ise) {
                // this usually means the entry is no longer in the map.
                throw new ConcurrentModificationException(ise);
            }
            (k, v);
        }
    }

使用:

        Map<String,User> map =new HashMap<>();
        ("1",new User("aa",10));
        ("2",new User("bb",11));
        ("3",new User("cc",12));

        //匹配输出,匹配项可以为list集合元素的属性(成员变量)
        ((t,v)->("id : " + t + " User : " + v));

 

相关文章