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.
- Collections can now be iterated over using the forEach() method, passing in a lambda expression which defines the code to execute on each item in the collection.
- The concept of a stream is introduced, with a new API for transforming collections. Using lambda expressions, we can now write code much more succinctly in common cases where we want to iterate through a collection, performing operations on the items in question and gathering the results into a new collection.
- Various utility classes and methods have been added to make working with lambda expressions easier and less verbose than it would have been with the language extension alone. For example, while we can use a lambda expression instead of a Comparator implementation, static methods have also been added to Comparator to make it easier to write the lambda expression that we need.
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:
list.forEach(System.out::println);
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);
System.out.println(str);
});
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.