Java 8 Iterable.forEach() vs foreach loop

前端 未结 8 1321
暗喜
暗喜 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:22

    The advantage of Java 1.8 forEach method over 1.7 Enhanced for loop is that while writing code you can focus on business logic only.

    forEach method takes java.util.function.Consumer object as an argument, so It helps in having our business logic at a separate location that you can reuse it anytime.

    Have look at below snippet,

    • Here I have created new Class that will override accept class method from Consumer Class, where you can add additional functionility, More than Iteration..!!!!!!

      class MyConsumer implements Consumer{
      
          @Override
          public void accept(Integer o) {
              System.out.println("Here you can also add your business logic that will work with Iteration and you can reuse it."+o);
          }
      }
      
      public class ForEachConsumer {
      
          public static void main(String[] args) {
      
              // Creating simple ArrayList.
              ArrayList aList = new ArrayList<>();
              for(int i=1;i<=10;i++) aList.add(i);
      
              //Calling forEach with customized Iterator.
              MyConsumer consumer = new MyConsumer();
              aList.forEach(consumer);
      
      
              // Using Lambda Expression for Consumer. (Functional Interface) 
              Consumer lambda = (Integer o) ->{
                  System.out.println("Using Lambda Expression to iterate and do something else(BI).. "+o);
              };
              aList.forEach(lambda);
      
              // Using Anonymous Inner Class.
              aList.forEach(new Consumer(){
                  @Override
                  public void accept(Integer o) {
                      System.out.println("Calling with Anonymous Inner Class "+o);
                  }
              });
          }
      }
      

提交回复
热议问题