DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

[DZone Research] Observability + Performance: We want to hear your experience and insights. Join us for our annual survey (enter to win $$).

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Eclipse JNoSQL 1.0.2: Empowering Java With NoSQL Database Flexibility
  • Leveraging Weka Library for Facebook Data Analysis
  • Scalable Rate Limiting in Java With Code Examples: Managing Multiple Instances
  • How To Get and Set PDF Form Fields in Java

Trending

  • LLMs for Bad Content Detection: Pros and Cons
  • Docker and Kubernetes Transforming Modern Deployment
  • AI for Web Devs: Project Introduction and Setup
  • Scalable Rate Limiting in Java With Code Examples: Managing Multiple Instances
  1. DZone
  2. Coding
  3. Java
  4. Functional Java: Traversing a List in a Functional Way

Functional Java: Traversing a List in a Functional Way

Learn more about traversing a List — in a functional way!

Rishi Khandelwal user avatar by
Rishi Khandelwal
·
Aug. 06, 19 · Tutorial
Like (6)
Save
Tweet
Share
37.11K Views

Join the DZone community and get the full member experience.

Join For Free

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 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!

Java (programming language)

Published at DZone with permission of Rishi Khandelwal, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Eclipse JNoSQL 1.0.2: Empowering Java With NoSQL Database Flexibility
  • Leveraging Weka Library for Facebook Data Analysis
  • Scalable Rate Limiting in Java With Code Examples: Managing Multiple Instances
  • How To Get and Set PDF Form Fields in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: