欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

在Java8的foreach()中使用return

程序员文章站 2022-07-12 20:29:42
...

在使用jdb8的lambda表达式遍历集合时,如果想要跳过当次循环执行下个循环,可以使用return,使用continue会编辑报错。

public class T {
    private static StateQueue<String> queue = new StateQueue<>();

    /**   
     * <p><b>Description:</b> </p>  
     * @param args  
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {
        
        queue.put("1");
        queue.put("2");
        queue.put("3");
        queue.put("4");
        queue.put("");
        queue.put("5");
        queue.put("6");
        new Thread(()-> {
            while(true) {
                System.out.println("处理……");
                String eventId = null;
                try {
                    eventId = queue.take();
                } catch (InterruptedException e) {
                    continue;
                }
                if(StringUtils.isEmpty(eventId)) continue;
                
            }
        }).start();
        
        queue.forEach(q->{
            if("".equals(q)) return;
            
            System.out.println("遍历"+q);
        });
    }

以下为执行结果截图:

在Java8的foreach()中使用return 

可以看出,return在这里并没有跳出循环,而是相当于了continue。