Extracting the elements of the Java Collection- The Java 8 way
We all have extensively used Collection classes like List, Map and their derived versions. And each time we used them we had to iterate through them to either find some element or update the elements or find different elements matching some condition. Consider a List of Person as shown below:
List<Person> personList = new ArrayList<>();
personList.add(new Person("Virat", "Kohli",22));
personList.add(new Person("Arun", "Kumar",25));
personList.add(new Person("Rajesh", "Mohan", 32));
personList.add(new Person("Rahul", "Dravid", 35));
To find out all the Person instances with age greater than 30, we would do:
List<Person> olderThan30OldWay = new ArrayList<>();
for ( Person p : personList){
if ( p.age >= 30){
olderThan30OldWay.add(p);
}
}
System.out.println(olderThan30OldWay);
and this gives me the output as:
[Rajesh Mohan, 32, Rahul Dravid, 35]
The code is easy to write, but is it not a bit more verbose, especially the iteration part? Why would we have to iterate? Would it not be cool if there was an API which would iterate the contents and give us the end result i.e we give the source List and use a series of method calls to get us the result List we are looking for? Yes, this is possible in other languages like Scala, Groovy which support passing closures and also support internal iteration. But is there a solution for Java developers? Yes, this exact problem is being solved by introducing support for Lambda Expressions(closures) and a enhanced Collection API to leverage the lambda expression support. The sad news is that it’s going to be part of Java 8 and will take some time to be into mainstream development.
Leveraging the Java 8 enhancements to the above scenario
As I said before the Collections API is being enhanced to support the use of Lambda Expression and more about it can be read here. Instead of adding all the new APIs to the Collection class the JDK team created a new concept called “Stream” and added most of the APIs in that class. “Stream” is a sequence of elements obtained from the Collection from which it is created. To read more about the origin of Stream class please refer to this document.
To implement the example I started with using the enhancements in Java 8 we would be using few new APIs namely: stream(), filter(), collect(), Collectors.toCollection().
stream(): Uses the collection on which this API is called to create an instance of Stream class.
filter():This method accepts a lambda expression which takes in one parameter and returns a boolean value. This lambda expression is written as a replacement for implementing the Predicate class.
collect(): There are 2 overloaded versions of this method. The one I am using here takes an instance of Collector. This method takes the contents of the stream and constructs another collection. This construction logic is defined by the Collector.
Collectors.toCollection(): Collectors is a factory for Collector. And the toCollection() takes a Lambda expression/Method reference which should return a new instance of any derivatives of Collection class.
With brief introduction to the APIs used, let me show the code which is equivalent to the first code sample:
List<Person> olderThan30 =
//Create a Stream from the personList
personList.stream().
//filter the element to select only those with age >= 30
filter(p -> p.age >= 30).
//put those filtered elements into a new List.
collect(Collectors.toCollection(() -> new ArrayList<Person>()));
System.out.println(olderThan30);
The above code uses both Internal iteration and lambda expressions to make it intuitive, concise and soothing to the eye.
If you are not familiar with the idea of Lambda Expressions, check out my previous entry which covers in brief about Lambda expressions.
Related posts:
- Using Lambda Expression to sort a List in Java 8 using Netbeans Lambda Support Tweet As part of JSR 335 Lambda expressions are being...
- Whats in store for Project Lambda in Java 8? Tweet There are lot of things happening in the Project...
- UnsupportedOperation exception while using Map in Java Tweet You must have encountered UnsupportedOperation exception while using Map,...
Related posts brought to you by Yet Another Related Posts Plugin.
One Response to Extracting the elements of the Java Collection- The Java 8 way
Connect to us …
Archives
- May 2013 (8)
- April 2013 (6)
- March 2013 (6)
- January 2013 (5)
- November 2012 (2)
- September 2012 (1)
- July 2012 (5)
- June 2012 (1)
- May 2012 (4)
- April 2012 (7)
- March 2012 (2)
- February 2012 (4)
- December 2011 (2)
- November 2011 (4)
- October 2011 (2)
- September 2011 (1)
- August 2011 (1)
- July 2011 (1)
- June 2011 (1)
- May 2011 (1)
- April 2011 (1)
- February 2011 (4)
- December 2010 (3)
- November 2010 (2)
- September 2010 (2)
- August 2010 (3)
- May 2010 (2)
- March 2010 (6)
- December 2009 (1)
- November 2009 (3)
- July 2009 (6)
- June 2009 (3)
- May 2009 (1)
- April 2009 (6)
- March 2009 (1)
- January 2009 (1)
- December 2008 (8)
- November 2008 (5)
- October 2008 (6)
- September 2008 (4)
- August 2008 (8)
- July 2008 (19)
- June 2008 (29)
- May 2008 (27)
- April 2008 (11)
- March 2008 (8)
- February 2008 (22)
- January 2008 (3)
Send To Readmill
Send to ReadmillRecent Posts
- How to create ADF TreeTable programmatically?
- Book review: The Object-Oriented Thought Process
- How to show links in ADF Messages
- Runtime Polymorphism in Java
- Understanding RowKey values in ADF TreeTable
- Train Wreck Pattern – A much improved implementation in Java 8
- Converting a List into comma separated value string in Java
- A simple application of Lambda Expressions in Java 8
- Template Method Pattern- Using Lambda Expressions, Default Methods
- First look at Learning Play! Framework 2
Disclaimer
Some of the links contained within this site have my referral id, which provides me with a small commission for each sale. Thank you for your support.










[...] I was working on the samples for this post using the Nebeans nightly builds with support for Lambda Expressions downloaded from here. I [...]