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

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

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

  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Reducing Boilerplate Code With Annotations
  • Leveraging Weka Library for Facebook Data Analysis
  • Scalable Rate Limiting in Java With Code Examples: Managing Multiple Instances

Trending

  • Chronicle Services: Low Latency Java Microservices Without Pain
  • Common Problems in Redux With React Native
  • Understanding Europe's Cyber Resilience Act and What It Means for You
  • AWS vs. Azure vs. Google Cloud: Comparing the Top Cloud Providers
  1. DZone
  2. Coding
  3. Java
  4. Getting Rid of Boilerplate Code with Java Lambda Expressions

Getting Rid of Boilerplate Code with Java Lambda Expressions

Edwin Dalorzo user avatar by
Edwin Dalorzo
·
Apr. 10, 13 · Interview
Like (0)
Save
Tweet
Share
5.97K Views

Join the DZone community and get the full member experience.

Join For Free

As I have mentioned in a previous post, there is nothing we can do with lambda expressions that we could not do without them. Basically because we can implement a similar idiom in Java using anonymous classes. The problem is that anonymous classes require a lot of boilerplate code.

To demonstrate the value of lambda expressions as a tool to achieve more succinct code in this post I will develop some classical high-order functions from scratch.

Filtering

Let’s consider the existence of an interface called Predicate defined as follows:

interface Predicate<T> {
   public boolean test(T t);
}

And now, let’s say we would like to use the Predicate interface to filter the elements of any given list based on a given predicate. So, we could define something as follows:

static <T> List<T> filter(Predicate<T> predicate, List<T> source) {
    List<T> destiny = new ArrayList<>();
    for(T item : source) {
      if(predicate.test(item)){
         destiny.add(item);
      }
    }
   return destiny;
}

Now, consider that we had a list of numbers, and we would like to filter only those that are odd. Traditionally, in Java, we would use an anonymous class to define the predicate, something like this:

List<Integer> numbers = asList(1,2,3,4,5,6,7,8,9);
List<Integer> onlyOdds = filter(new Predicate<Integer>(){
                           @Override
                           public boolean test(Integer n) {
                              return n % 2 != 0;
                           }
                          }, numbers);

But consider all the boilerplate code that was necessary here to simply say that we would like to take a value n and check if it is an odd number. Clearly this does not look good.

In Java 8, we could get rid of all this mess by simply implementing our predicate using a lambda expression, as follows:

List<Integer> numbers = asList(1,2,3,4,5,6,7,8,9);
List<Integer> onlyOdds = filter(n –> n % 2 !=0, numbers);

Here, the lambda expression will be evaluated to an instance of the type Predicate, its argument n, corresponds to the argument expected by its method test, and the body of the expressions represents the implementation of the method.

Mapping

Let’s consider now the existence of an interface Function defined as follows:

interface Function<T,R> {
   public R apply(T t);
}

And now, let’s say we would like to use this functional interface to transform the elements of a list from one value to another. So, we could define a method as follows:

static <T,R> List<R> map(Function<T,R> function, List<T> source){
   List<R> destiny = new ArrayList<>();
   for(T item : source) {
      R value = function.apply(item);
      destiny.add(value);
   }
   return destiny;
}

Now, consider that we had a list of strings representing numbers and we would like to convert them to their corresponding integer values. Once again, in the traditional model we could use Java anonymous classes for this, like so:

List<String> digits = asList("1","2","3","4","5","6","7","8","9");
List<Integer> numbers = map(new Function<String, Integer() {
                          @Override
                          public Integer apply(String digit) {
                            return Integer.valueOf(digit);
                          }
                        }digits);

Once again, consider all the boilerplate code necessary for something as simple as converting a string to an integer. We could get rid of all that using a lambda expression as follows:

List<String> digits = asList("1","2","3","4","5","6","7","8","9");
List<Integer> numbers = map(s –> Integer.valueOf(s), digits);

This is clearly much better. Once again, the lambda expression evaluates to an instance of the type Function<String, Integer> where s represents the argument for its function apply and the body of the lambda expression represents what the function would return in its body.

Reducing

Let’s consider now the existence of an interface BinaryOperator defined as follows:

interface BinaryOperator<T> {
   public T apply(T left, T right);
}

And now we would like to use this functional interface to reduce the values from a list to a single value. So, we could use it as follows:

static <T> T reduce(BinaryOperator<T> operator,T seed, List<T> source){
    for(T item: source) {
       seed = operator.apply(seed, item);
    }
    return seed;
}

Consider now that we have a list of numbers and we would like to obtain to summation of them all. Once more, if we intend to use this code as we traditionally have done before the release of Java 8 we would be forced to to following verbose definition, as follows:

List<Integer> numbers = asList(1,2,3,4,5);
Integer sum = reduce(new BinaryOperator<Integer>() {
                     @Override
                     public Integer apply(Integer left, Integer right){
                        return left + right;
                     }
                    },0,numbers);

This code can be greatly simplified by the use of a lambda expression, as follows:

List<Integer> numbers = asList(1,2,3,4,5);
Integer sum = reduce( (x,y) –> x + y, 0, numbers);

Where (x,y) correspond to the two arguments left and right that the function apply receives, and the body of the expressions would be what it would return. Notice that, since in this case we have to specify two arguments, the lambda expressions is required to specify them within parenthesis, otherwise the compiler could determine which arguments are for the lambda expression and which are for the reduce method.

Consuming

Let’s consider now the existence of a functional interface Consumer, defined as follows:

interface Consumer<T> {
   public void accept(T t);
}

Now we could use implementations of this interface to consume the elements of a list and do something with them, like printing them to the main output or sending them over the network, or whatever we could consider appropriate. For this example, let’s just print them to the output:

static <T> void forEach(Consumer<T> consumer, List<T> source) {
    for(T item: source) {
       consumer.accept(item);
    }
}

Look at all the boilerplate code necessary to create a consumer to simply print all the elements of a list:

List<Integer> numbers = asList(1,2,3,4,5);
forEach(new Consumer<Integer>(){
   @Override
   public void accept(Integer n) {
      System.out.println(n);
   }
},numbers);

However, now we could use a simple lambda expression to implement equivalent functionality as follows:

List<Integer> numbers = asList(1,2,3,4,5);
forEach(n –> { System.out.println(n); }, numbers);

The syntax differs a bit from the previous cases because in this case the method we intend to implement through the lambda expression returns void, and that is why we use a code block to signify that the type of the lambda expression is also void.

Producing

Let’s consider now the existence of a functional interface Supplier as follows:

interface Supplier<T> {
   public T get();
}

A classical idiom is to use this type of interface to encapsulate an expensive calculation and differ its evaluation until needed, something typically known as lazy evaluation. For example:

public static int generateX() {
  return 0;
}
 
public static int generateY() {
   //some expensive calculation here
   return 1;
}
 
public static int calculate(Supplier<Integer> thunkOfX,
                            Supplier<Integer> thunkOfY) {
   int x = thunkOfX.get();
   if(x==0)
      return 0;
   else
      return x + thunkOfY.get();
}

By means of passing two suppliers here we defer the evaluation of x and y until needed. As you can see, if x is equal to 0, y is never needed. So, by using this idiom we avoid spending a lot of time in a expensive calculation unnecessarily.

Before lambda expressions, the invocation of calculation would have implied a lot of boilerplate code as follows:

calculate(new Supplier<Integer>() {
  @Override
  public Integer get() {
     return generateX();
  }
},
new Supplier<Integer>() {
   @Override
   public Integer get() {
     return generateY();
   }
});

However, using lambda expressions, this a one-liner:

calculate( () –> generateX(), () –> generateY() );

Clearly this is much better.

Summary of Lambda Syntax

So, these are different ways to define lambda expressions:

Predicate<Integer> isOdd = n –> n % 2 == 0;
Function<String, Integer> atoi = s –> Integer.valueOf(s);
BinaryOperator<Integer> product = (x, y) –> x * y
Comparator<Integer> maxInt = (x,y) –> x > y ? x : y;
Consumer<String> printer = s –> { System.out.println(s); };
Supplier<String> producer = () –> "Hello World";
Runnable task = () –> { System.out.println("I am a runnable task");  };

In summary, lambda expressions are a great tool to get rid of all the boilerplate required by the clunky Java syntax of anonymous classes. The new API for Streams makes extensive use of this new syntax:

int oddSum = asList("1","2","3","4","5").stream()
                                        .map(n –> Integer.valueOf(n))
                                        .filter(n –> n % 2 != 0)
                                        .reduce(0, (x,y) –> x + y); // 9





 

Boilerplate code Java (programming language)

Published at DZone with permission of Edwin Dalorzo. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Reducing Boilerplate Code With Annotations
  • Leveraging Weka Library for Facebook Data Analysis
  • Scalable Rate Limiting in Java With Code Examples: Managing Multiple Instances

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: