Advertisements

Functional Java: Traversing a list in a functional way

Reading Time: 3 minutes

In 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 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. 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 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 which we can use with forEach() and that is method reference:

players.forEach(System.out::println);

That’s all about the traversing a list in a functional way. Let’s give it a try once and I am sure you will gonna love this functional way.

There are many other functions with a list which we will be discussing in my upcoming blogs. Stay Tuned.

blog_footer

Advertisements

Written by 

Rishi is a Lead Consultant, with experience of more than 7 years. Rishi is product focused developer who loves developing both front-end user interfaces and scalable back-end infrastructure. He is a good team player, quick learner and a humble person. He has good time management skills, aimed to give best results and fully dedicated towards his work & responsibilities. He is able to work as individual and as well as in team. He loves to share his knowledge, therefore he often writes technical blogs.

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!