Monday, September 3, 2018

Do you know - Series 2: Stream Operation: Java

This post talks about different options available for iterating over a List.

  • using iterator  - Jdk 1.2
          List listItems = new LinkedList();
          . . .
          Iterator itr = listItems.iterator();
          while(itr.hasNext()) {
                String item =;

  • using for loop - Jdk 1.5
          for(String item: listItems) {
  • using for...each loop - Jdk 1.8
          listItems.forEach(item -> doSomething(item));
  • using Streams  - Jdk 1.8
 -> doSomething(item)).count();
          Stream.of("a", "b", "c").filter(something).map(item -> doSomething(item)).count();

Please note that the Streams can not be reused once it is done with any terminal    operations.  When you try to reuse you will get IlleagalStateException as the stream is already operated and closed. 

If you want to reuse and avoid this exception then you may keep the above statement local scope or create a new stream every time using stream Supplier as below.
          Supplier < Stream < String >> streamSupplier = () -> Stream.of("a", "b", "c");


No comments:

Post a Comment

Do you know - Series - 4: Boxing and Unboxing - Integer assignment and comparison

We know about boxing and unboxing in Java. It is about automatic conversion of primitive type value into its Wrapper Object equivalent type...