Enhanced Collections API in Java 8- Supports Lambda expressions

SHARE & COMMENT :

Continuing with our exploration of JSR-335 lets look at some of the enhancements to the collections API as part of the Project Lambda effort. A new feature in the language and not supported by the existing API is just not what the programmers would want. And this is what Brian Goetz and his team working on JSR-335 realized. It was not an easy task of enhancing the existing API without breaking uncountable lines of code. That was a challenge which they took up and managed to get around this by introducing the concept of defender methods.

also read:

To outline the major changes in collection API:

  • Support for internal iteration by providing methods like forEach, filter, map and others which are added to the Iterable interface with default implementations (Defender methods).
  • Explicit parallel APIs for greater parallelism support. These can be combined with Fork/Join to divide the tasks
  • Greater stress on immutability and avoiding in-place mutation which was done in the conventional for-each loops

All of these are possible by giving the API/method power to decide its iteration. And the caller would pass in a block of code which would be applied on each of the element or elements decided by the API/method being invoked. That’s pretty much of the theory, lets see it in action on a List of integers from 1 to 10.

List<Integer> counts = new ArrayList<Integer>;();
for(int i=1;i <= 10; i++){
  counts.add(i);
}

Iterating through the elements in the list:

//Using external iterators
System.out.println('Using external iterator');
for(Integer i : counts){
  System.out.print(i+' ');
}
System.out.println();

versus

//Using internal iterators
System.out.println('Using internal iterator');
//Passing a code block to forEach method
counts.forEach(i -> {System.out.print(i*2+' ')});
System.out.println();

Very concise right? Digging into forEach method introduced in Iterable interface, it is implemented as:

void forEach(Block<? super T> block) default {
  Iterables.forEach(this, block);
}

if you are confused about the use of “default” keyword, then please read about it here. Iterables is a new class to be introduced in Java 8 and the forEach method in Iterables expects an collection/something which can be iterated and the block of code to apply on the each element iterated, the implementation is:

public static <T> Iterable<T> 
   forEach(final Iterable<? extends T> iterable,
           final Block<? super T> block) {
  Objects.requireNonNull(iterable);
  Objects.requireNonNull(block);
  for (T each : iterable) {
    block.apply(each);
  }

  return (Iterable<T>) iterable;
}

Looks like forEach method does nothing different from the older for-each loop, that’s how forEach ought to work. If you want to maintain immutability you can use a different method which I will write a little later. But for now, forEach iterates through the iterable and applies the block to each of the element. Going into the Block and apply method would be out of scope of this article, lets look at it in a different article.

Lets explore a bit further and print all the even elements of the list.
Using external iteration ( for-each loop) we would have

for ( Integer i : counts){
  if ( i % 2 == 0 ){
    System.out.print(i+' ');
  }
}

and using the new APIs:

//filter evaluates the block
//and returns a new iterable.
counts.filter(i -> i%2 == 0)
      .forEach(i-> {System.out.print(i+' ');});

the filter method doesn’t create a new collection instead it creates a new Iterable. The difference it makes is that there is no intermediate collection created after filter is invoked.

Another example before we close- lets multiply all the odd elements by 2 and create a new list.
Using the for-each loop, this can be done as:

List<Integer> newCounts = new ArrayList<Integer>();
for(Integer i : counts){
  if ( i % 2 != 0 ){
      newCounts.add(i*2);
  }
}
for(Integer i : newCounts){
System.out.print(i+' ');
}

and the same using new API:

List<Integer>; newCountsNew = new ArrayList<Integer>;();
counts.filter(i -> i % 2 != 0)
      .map(i -> i*2)
      .into(newCountsNew);
newCountsNew.forEach(i -> {System.out.print(i+' ');});

Apart from the other benefits mentioned at the beginning the above code which uses new APIs is more readable than the one which uses for-each.

If you want to read more about the state of the APIs with respect to the lambda expressions, please do so here.
The examples used above can be found here as well.

Comments

comments

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Comments

  1. Amit Phaltankar says:

    Really nice post. Java 8 Features are really cool and surely be a big game changers.
    Java’s long awaited collections framework modification is on the way. The changes like Stream, internal iterations, parallelism are really exciting. I have posted an Introduction to Java 8′s Collection Framework Enhancements for Lambda Expressions or Closures. Please have a look at it.

  2. Hi,

    it is very clear and understandable format.Could you explain about methods are filter,map,into methods in which internally what happens.

    Thanks in Advance

Trackbacks

  1. [...] java.util.Objects class. I came across this usage of class while I was browsing through the updated Java 8 collections [...]

  2. [...] Overview of Collections API additions: http://www.javabeat.net/2012/05/enhanced-collections-api-in-java-8-supports-lambda-expressions/ [...]

  3. [...] Enhanced Collections API in Java 8 supports Lambda expressions. [...]

  4. JavaPins says:

    Enhanced Collections API in Java 8- Supports Lambda expressions…

    Thank you for submitting this cool story – Trackback from JavaPins…

  5. […] is a basic tutorial explaining about the APIs define under the collection package in Java. We encounter numerous questions from our readers to clarify the differences on these […]

  6. […] toString method is, it extends to the objects containing references to these instances, especially collections. For example, it is better to see the display mapping: “Jenny = zip @ th163b91″ than […]

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better