lambda - foreach

本文详细介绍了Java 1.8中lambda语法的使用,通过map和list的foreach遍历,对比了传统for循环与lambda表达式的效率,并展示了如何在Map和List中运用BiConsumer和Consumer接口。

lambda - foreach

lambda 语法格式:

(parameters) -> expression

(parameters) -> {statements;}

    /**
     * Map<String,Integer></>
     */
    public static void testMap() {
        Map<String, Integer> map = new HashMap<>();
        map.put("a", 1);
        map.put("b", 2);
        map.put("c", 3);

        Date now = new Date();
        // foreach 遍历
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println("key -> " + entry.getKey() + " value -> " + entry.getValue());
        }
        Date end = new Date();
        System.out.println(end.getTime() - now.getTime());
        System.out.println("--------------------");
        Date now2 = new Date();
        // lambda foreach 遍历
        map.forEach((k, v) -> System.out.println("key -> " + k + " value -> " + v));
        Date end2 = new Date();
        System.out.println(end2.getTime() - now2.getTime());
    }

 

    /**
     * List<String></>
     */
    public static void testList() {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("v");
        list.add("b");
        // foreach 遍历
        for (String s : list) {
            System.out.println(s);
        }
        System.out.println("--------------------");
        // lambda foreach 遍历
        list.forEach(iem -> System.out.println(iem));
        list.forEach(System.out::println);
    }

jdk 1.8  Map<K,V>

   /**
     * Performs the given action for each entry in this map until all entries
     * have been processed or the action throws an exception.   Unless
     * otherwise specified by the implementing class, actions are performed in
     * the order of entry set iteration (if an iteration order is specified.)
     * Exceptions thrown by the action are relayed to the caller.
     *
     * @implSpec
     * The default implementation is equivalent to, for this {@code map}:
     * <pre> {@code
     * for (Map.Entry<K, V> entry : map.entrySet())
     *     action.accept(entry.getKey(), entry.getValue());
     * }</pre>
     *
     * The default implementation makes no guarantees about synchronization
     * or atomicity properties of this method. Any implementation providing
     * atomicity guarantees must override this method and document its
     * concurrency properties.
     *
     * @param action The action to be performed for each entry
     * @throws NullPointerException if the specified action is null
     * @throws ConcurrentModificationException if an entry is found to be
     * removed during iteration
     * @since 1.8
     */
    default void forEach(BiConsumer<? super K, ? super V> action) {
        Objects.requireNonNull(action);
        for (Map.Entry<K, V> entry : entrySet()) {
            K k;
            V v;
            try {
                k = entry.getKey();
                v = entry.getValue();
            } catch(IllegalStateException ise) {
                // this usually means the entry is no longer in the map.
                throw new ConcurrentModificationException(ise);
            }
            action.accept(k, v);
        }
    }

jdk 1.8  List<T>

    /**
     * Performs the given action for each element of the {@code Iterable}
     * until all elements have been processed or the action throws an
     * exception.  Unless otherwise specified by the implementing class,
     * actions are performed in the order of iteration (if an iteration order
     * is specified).  Exceptions thrown by the action are relayed to the
     * caller.
     *
     * @implSpec
     * <p>The default implementation behaves as if:
     * <pre>{@code
     *     for (T t : this)
     *         action.accept(t);
     * }</pre>
     *
     * @param action The action to be performed for each element
     * @throws NullPointerException if the specified action is null
     * @since 1.8
     */
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

 

 

 

 

 

 

下面是一个完整的 Java 程序,满足你的所有要求: ### ✅ 题目要求回顾: 1. 创建 `List<Integer>` 集合; 2. 添加元素:10、20、30、40、50; 3. 使用 **迭代器(Iterator)** 遍历并打印; 4. 删除值为 30 的元素; 5. 再使用 **forEach** 遍历并打印剩余元素。 --- ### ✅ 完整代码实现: ```java import java.util.*; public class ListOperationExample { public static void main(String[] args) { // 1. 创建 List<Integer> 并添加元素 List<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.add(30); list.add(40); list.add(50); System.out.println("使用 Iterator 遍历(删除前):"); // 2. 使用迭代器遍历并删除值为30的元素 Iterator<Integer> iterator = list.iterator(); while (iterator.hasNext()) { Integer value = iterator.next(); System.out.print(value + " "); if (value == 30) { iterator.remove(); // 安全删除 } } System.out.println("\n值为30的元素已删除。"); // 3. 使用 forEach 遍历打印删除后的集合 System.out.println("使用 forEach 遍历(删除后):"); list.forEach(System.out::println); } } ``` --- ### ✅ 输出结果: ``` 使用 Iterator 遍历(删除前): 10 20 30 40 50 值为30的元素已删除。 使用 forEach 遍历(删除后): 10 20 40 50 ``` --- ### 🔍 代码解释 | 代码段 | 说明 | |-------|------| | `List<Integer> list = new ArrayList<>();` | 创建一个可变的整数列表 | | `list.add(...)` | 添加指定元素到列表末尾 | | `iterator()` | 获取该集合的迭代器对象 | | `hasNext()` / `next()` | 判断是否有下一个元素,并获取它 | | `iterator.remove()` | 在遍历过程中安全删除当前元素(这是唯一安全方式) | | `list.forEach(System.out::println)` | 使用 Lambda 方式遍历输出每个元素 | > ⚠️ 注意:不能在普通 for-each 循环中直接删除元素,否则会抛出 `ConcurrentModificationException`。而使用 `Iterator` 的 `remove()` 方法是线程安全且合法的删除方式。 --- ### ✅ 扩展建议 你也可以使用增强的写法来简化添加过程: ```java List<Integer> list = new ArrayList<>(Arrays.asList(10, 20, 30, 40, 50)); ``` 或者使用 Java 9+ 的不可变列表构造后再转为可变列表: ```java List<Integer> list = new ArrayList<>(List.of(10, 20, 30, 40, 50)); ``` 但注意:`List.of()` 和 `Arrays.asList()` 返回的是固定大小的列表,不能直接增删元素,所以需要包装成新的 `ArrayList`。 --- ###
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值