list.forEach usage

list.forEach uses return to jump out of this loop (the function is similar to the continue of a for loop), and there is no jump out of the loop function (that is, no break function of the for loop)

Source code

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);
        }

    }
}

operation result

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

stream().anyMatch

  • Code
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);
}
  • result
================
================
================
================
flag=false
+++++++++++++++++++++++++
aa=true

Guess you like

Origin blog.csdn.net/thebigdipperbdx/article/details/108336127