Java 8 Iterable.forEach() vs foreach loop

前端 未结 8 1277
暗喜
暗喜 2020-11-22 14:36

Which of the following is better practice in Java 8?

Java 8:

joins.forEach(join -> mIrc.join(mSession, join));

Java 7:



        
8条回答
  •  借酒劲吻你
    2020-11-22 15:14

    One of most upleasing functional forEach's limitations is lack of checked exceptions support.

    One possible workaround is to replace terminal forEach with plain old foreach loop:

        Stream stream = Stream.of("", "1", "2", "3").filter(s -> !s.isEmpty());
        Iterable iterable = stream::iterator;
        for (String s : iterable) {
            fileWriter.append(s);
        }
    

    Here is list of most popular questions with other workarounds on checked exception handling within lambdas and streams:

    Java 8 Lambda function that throws exception?

    Java 8: Lambda-Streams, Filter by Method with Exception

    How can I throw CHECKED exceptions from inside Java 8 streams?

    Java 8: Mandatory checked exceptions handling in lambda expressions. Why mandatory, not optional?

提交回复
热议问题