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();
          listItems.add("a");
          . . .
          listItems.add(n);
          Iterator itr = listItems.iterator();
          while(itr.hasNext()) {
                String item = itr.next();
                doSomething(item);
         }

  • using for loop - Jdk 1.5
          for(String item: listItems) {
                 doSomething(item);
          }
  • using for...each loop - Jdk 1.8
          listItems.forEach(item -> doSomething(item));
  • using Streams  - Jdk 1.8
          listItems.stream().filter(something).map(item -> doSomething(item)).count();
          or
          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");
          

                  

Sunday, September 2, 2018

Do you know - Series 1: Null Check: Java


The idea of this post is to just highlight some of the features in Java which we may need in our day to day development work.

  • The different ways to check null value of an Object
    • null != obj
    • Objects.nonNull(obj) - from java.util
    • filter(Objects::nonNull) - when used with Lambda
    • Optional.ofNullable(obj).ifPresent(o —> o.getValue());
    • StringUtils.isNotEmpty(obj) - froorg.apache.commons.lang3
      • this takes care of both empty and null checks
    • filter(StringUtils::isNotEmpty) - when used with Lambda

  • Do something if nonNull and something else if Null

    • Optional.ofNullable(obj).map(obj -> {
          doSomething(obj)
          return obj;
      }).orElseGet(() -> {
          logForNull();
          return null;
      });

      HereIf the object is nonNull, then only the value will be applied to the mapping function

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...