list.forEach 用法

list.forEach 用 return 跳出本次循环(作用类似 for 循环的 continue),无跳出循环功能(即无 for 循环的 break 功能)

源码

package com.me.address;

import java.util.Arrays;
import java.util.List;

/**
 * @author yanyg
 * @since 2020/9/1
 */
public class ListforEachTest {
    
    
    private static final String DEFAULT_STR = "7777";

    public static void main(String[] args) {
    
    
        List<String> list = Arrays.asList("6666", "7777", "8888", "9999");
        list.forEach(t -> {
    
    
            if (t.equals(DEFAULT_STR)) {
    
    
                // 跳槽本次循环,继续下一次循环,类似 continue
                return;
            }
            System.out.println(t);
        });
        System.out.println("=====================================");
        for (String t : list) {
    
    
            if (t.equals(DEFAULT_STR)) {
    
    
                // 跳槽本次循环,继续下一次循环
                continue;
            }
            System.out.println(t);
        }
        System.out.println("=====================================");
        for (String t : list) {
    
    
            if (t.equals(DEFAULT_STR)) {
    
    
                // 跳出循环
                break;
            }
            System.out.println(t);
        }

    }
}

运行结果

6666
8888
9999
=====================================
6666
8888
9999
=====================================
6666

stream().anyMatch

  • 代码
public static void main(String[] args) {
    
    

    List<String> list = Arrays.asList("6666", "7777", "8888", "9999");
    /**
     * 每次都执行一次,flag 是最后一次匹配的值
     * 可以设置变量存储想要的 true 或  false
     */
    boolean flag = list.stream().anyMatch(t -> {
    
    
        System.out.println("================");
        if ("777".equals(t)) {
    
    
            return true;
        } else {
    
    
            return false;
        }
    });
    System.out.println("flag=" + flag);
    System.out.println("+++++++++++++++++++++++++");

    List<String> strs = Arrays.asList("a", "a", "a", "a", "b");
    // 判断的条件里,任意一个元素成功,返回true
    boolean aa = strs.stream().anyMatch(str -> str.equals("a"));
    System.out.println("aa=" + aa);
}
  • 结果
================
================
================
================
flag=false
+++++++++++++++++++++++++
aa=true

猜你喜欢

转载自blog.csdn.net/thebigdipperbdx/article/details/108336127