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

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

Related

  • Memory Leak Due to Uncleared ThreadLocal Variables
  • Beyond Java Streams: Exploring Alternative Functional Programming Approaches in Java
  • Java Enterprise Matters: Why It All Comes Back to Jakarta EE
  • How to Identify the Underlying Causes of Connection Timeout Errors for MongoDB With Java

Trending

  • Master SQL Performance Optimization: Step-by-Step Techniques With Case Studies
  • Integrating Apache Spark With Drools: A Loan Approval Demo
  • Mastering Fluent Bit: Controlling Logs With Fluent Bit on Kubernetes (Part 4)
  • Beyond Bytecode: Exploring the Relationship Between JVM, JIT, and Performance
  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!

By 
Rishi Khandelwal user avatar
Rishi Khandelwal
·
Aug. 06, 19 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
38.4K 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

  • Memory Leak Due to Uncleared ThreadLocal Variables
  • Beyond Java Streams: Exploring Alternative Functional Programming Approaches in Java
  • Java Enterprise Matters: Why It All Comes Back to Jakarta EE
  • How to Identify the Underlying Causes of Connection Timeout Errors for MongoDB With Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: