Using lambdas with Java Collections

Alongisde the introduction of lambdas, the Java 8 platform introduced some significant extensions to the Java Collections framework. These extensions are part of the overall Stream API. This API allows you to interact with Lists, Maps and other Collections using lambda expressions. They eliminate a lot of the tedious "boilerplate" code that is otherwise required to preform common tasks such as iterating through collections, filtering lists, partitioning data, enumerating the keys and values in a map, etc.

Iteration using forEach()

The Iterable interface has been extended with a new forEach() method. Instead of writing the following to print each item in a list of Strings:

for (String s : list) {
  ... do something with 's' ...

we can now write the following:

list.forEach(s -> ... do something with 's' ...)

Apart from the opportunity for more succinct code, the advantage of using forEach() is that individual classes may be able to iterate through the data structure more efficiently.

The forEach() method often provides a good opportunity to use method references. For example:

Iterating through key-value pairs in maps

The Map interface provides a special two-parameter version of forEach(). On each iteration, the parameters are filled in with the key and value of the mapping in question. For example:

map.forEach((key, value) -> {
	String str = String.format("'%s' is mapped to '%s'", key, value);

Next: learning more about the Stream API

The Stream API provides a powerful new API for manipulating data more easily in Java using lambdas.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.