Functional Java: Traversing a List in a Functional Way
Learn more about traversing a List — in a functional way!
Join the DZone community and get the full member experience.
Join For FreeIn this blog, we will see how we can traverse a list in Java in a functional way. Iterating through a list is a basic operation on a collection, but over the years, it's gone through a few significant changes. We'll begin with the old style and evolve to an example, enumerating a list of names to the elegant style.
Let's create a list first:
final List<String> players = Arrays.asList(“Virat”, “Rohit”, “Shikhar”, “Rahul”, “Rishabh”, “Hardik”, “MSD”);
Let's talk about the habitual way first, i.e. the imperative way.
for(int i = 0; i < players.size(); i++) {
System.out.println(players.get(i));
}
This is the verbose and error-prone way, and I personally don't like it. Here, we need to define the "how to" part as well, which we do not need to do in a functional way.
Java also offers a construct that is a bit more civilized than the good old for loop.
for(String name : players) {
System.out.println(name);
}
Under the hood, this form of iteration uses the Iterator interface and calls into its hasNext()
and next()
methods.
Both these versions are external iterators, which mix how we do it with what we'd like to achieve. We explicitly control the iteration with them, indicating where to start and here to end; the second version does that under the hood using the Iterator
methods. With explicit control, the break and continue statements can also help manage the iteration's flow of control.
The second construct has less ceremony than the first. Its style is better than the first if we don't intend to modify the collection at a particular index. Both of these styles, however, are imperative and we can dispense with them in modern Java.
There are quite a few reasons to favor the change to the functional style:
- The for loops are inherently sequential and are quite difficult to parallelize.
- Such loops are non-polymorphic; we get exactly what we ask for. We passed the collection to for instead of invoking a method (a polymorphic operation) on the collection to perform the task.
- At the design level, the code fails the "Tell, don't ask" principle. We ask for a specific iteration to be performed instead of leaving the details of the iteration to underlying libraries.
The Iterable interface has been enhanced in JDK 8 with a special method named forEach()
, which accepts a parameter of type Consumer. As the name indicates, an instance of Consumer will consume, through its accept()
method, what's given to it. Let's use the forEach()
method with the all-too-familiar anonymous inner class syntax.
players.forEach(new Consumer<String>() {
public void accept(final String name) {
System.out.println(name);
}
});
We changed just one thing: we traded in the old for loop for the new internal iterator forEach()
. As for the benefit, we went from specifying how to iterate to focusing on what we want to do for each element. The bad news is the code looks a lot more verbose.
Let's make one more change, replacing the anonymous inner class with a lambda expression.
players.forEach((final String name) -> System.out.println(name));
Here, forEach()
is a high order function.
Java compiler gives us the flexibility to leave off the type parameter; it will infer by its own.
players.forEach((name) -> System.out.println(name));
The Java compiler treats single-parameter lambda expressions as special. We can leave off the parentheses around the parameter if the parameter's type is inferred.
players.forEach(name -> System.out.println(name));
There is one more way in which we can use the forEach()
and that is method reference:
players.forEach(System.out::println);
That's all about the traversing a list in a functional way. Just give it a try at least once and I am sure you will love this functional approach.
There are many other functions using list, which we will be discussing in my upcoming blogs. Stay tuned!
Published at DZone with permission of Rishi Khandelwal, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments