Return from lambda forEach() in java

后端 未结 5 577
不知归路
不知归路 2020-12-13 02:14

I am trying to change some for-each loops to lambda forEach()-methods to discover the possibilities of lambda expressions. The following seems to be possible:

5条回答
  •  无人及你
    2020-12-13 02:25

    You can also throw an exception:

    Note:

    For the sake of readability each step of stream should be listed in new line.

    players.stream()
           .filter(player -> player.getName().contains(name))
           .findFirst()
           .orElseThrow(MyCustomRuntimeException::new);
    

    if your logic is loosely "exception driven" such as there is one place in your code that catches all exceptions and decides what to do next. Only use exception driven development when you can avoid littering your code base with multiples try-catch and throwing these exceptions are for very special cases that you expect them and can be handled properly.)

提交回复
热议问题