Simplify iterating over collections with Java 1.8

Old No Comments on Simplify iterating over collections with Java 1.8 1215

Iterating over collections has never been easier than this.


For those Java programmers who spend a great deal of time iterating and processing over collections like Vector, Stack, Map, etc., it is a pain to always insert a snippet of a for-each construct to iterate over a collection. It gets boring to always insert the snippet which also takes up a few lines of code, only to have you scrolling more over it.

Worry no more! Java 1.8 to the rescue!

Java 1.8 has introduced the forEach method in the collection classes to simplify iterating and processing collections. Simply pass a Consumer object. Consumer is a new functional interface which, as its name suggests, consumes the data provided to it.

Consumer interface, being a functional interface, has only one function to be overriden:

void accept(T t);

where T is the object type stored by the collection, passed onto accept method.

To further simplify code bloat due to anonymous classes produced to override accept, Java 1.8 has the feature to define lambda expressions, which are functional in nature and don’t require anonymous classes. They have the following basic syntax:

(args) -> { body }

Here is an example to map alphabets to integers and vice versa:

// Map characters to their positions in the alphabet.
Map<Character, Integer> charPositions=new HashMap<>();
charPositions.put('a', 1);
charPositions.put('b', 2);
charPositions.put('c', 3);
charPositions.put('d', 4);
charPositions.put('e', 5);
System.out.println(charPositions.toString());

// Reverse map such that integers denote alphabets.
Map<Integer, Character> reverseCharPositions=new HashMap<>();
charPositions.forEach( (c, i) -> { reverseCharPositions.put(i, c); } );
System.out.println(reverseCharPositions.toString());

The below line in the above snippet does all the job in one line:

charPositions.forEach( (c, i) -> { reverseCharPositions.put(i, c); } );

It takes the Character and Integer for each map entry and the symbol -> is followed by the code you want to be executed.

The same line can also be written by specifying types like this for more readability:

charPositions.forEach( (Character c, Integer i) -> { reverseCharPositions.put(i, c); } );

For more complicated processing, check out the Java Stream API introduced in Java 1.8. It is handy for processing large amounts of data in collections, both sequentially and in parallel.

So the next time you need to iterate and process a collection, simply use the forEach method provided with the collection and you are good to go, saving a few lines of code and also utilizing the new features of Java 1.8.

Author

Vivek Prajapati

A moderate level programmer interested in administration and Arduino. Familiar with C++, Java, PHP, C# with my favourite being C++. Just finished my bachelor's degree in IT.

Related Articles

Leave a comment

Back to Top