在Java8的foreach()中使用return

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

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

    /**   
     * 

Description:

* @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_第1张图片 

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

你可能感兴趣的:(On,Java,8,jdk8,lambda,jdk8,lambda循环,跳出当前循环)