BiConsumer Interface – Example

BiConsumer is a functional interface which represents an operation that accepts two input arguments and returns no result.

Lets see how we can use BiConsumer interface with an example.


import java.util.function.BiConsumer;

public class BiConsumerExample {
    
    public static void main(String[] args) {

        BiConsumer addConsumer = (x, y) -> {
            System.out.println("Add Operation result:" + (x+y));
        };

        BiConsumer subtractConsumer = (x, y) -> {
            System.out.println("Subtract Operation result:" + (x - y));
        };

        BiConsumer divideConsumer = (x, y) -> {
            System.out.println("Divide Operation result:" + (x / y));
        };

        BiConsumer multiplyConsumer = (x, y) -> {
            System.out.println("Multiply Operation result:" + (x * y));
        };
        addConsumer
            .andThen(subtractConsumer)
            .andThen(divideConsumer)
            .andThen(multiplyConsumer)
            .accept(10, 5);
    }

}

In the above program, we have defined 4 BiConsumer operations and each one takes two integer values as input and perform appropriate arithmetic operation and prints the result.

We can chain all these operations with andThen() method.

The output of the above program is given below.



Add Operation result:15
Subtract Operation result:5
Divide Operation result:2
Multiply Operation result:50


If an error occurs in any one of the operation, then the next operation would not be executed. For example, if you pass 10, 0 then java.lang.ArithmeticException would happen in the divide operation so it will not execute the multiply operation.

Refer below the code and its response.


import java.util.function.BiConsumer;

public class BiConsumerExample {

    public static void main(String[] args) {

        BiConsumer addConsumer = (x, y) -> {
            System.out.println("Add Operation result:" + (x+y));
        };

        BiConsumer subtractConsumer = (x, y) -> {
            System.out.println("Subtract Operation result:" + (x - y));
        };

        BiConsumer divideConsumer = (x, y) -> {
            System.out.println("Divide Operation result:" + (x / y));
        };

        BiConsumer multiplyConsumer = (x, y) -> {
            System.out.println("Multiply Operation result:" + (x * y));
        };
        addConsumer
            .andThen(subtractConsumer)
            .andThen(divideConsumer)
            .andThen(multiplyConsumer)
            .accept(10, 0);
    }

}



Add Operation result:10
Subtract Operation result:10
Exception in thread "main" java.lang.ArithmeticException: / by zero


IterableUtils – Example

In this post, we are going to see how we can use IterableUtils of Apache commons collections with an example.

Assume that you want to retrieve a key value from environmental variables. If its not available, then we would need to get it from system properties. If its not available even there, then we would need to assume a default value.

We can easily do it with an if else. But with the use of IterableUtils, we can avoid those boiler plate code.

Refer the below code.


import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.collections4.functors.NotNullPredicate;

import java.util.Arrays;

public class IterableMain {

    public static void main(String[] args) {
        //Get the default value
        System.out.println("Uses default app name:" + getKeyValue("APP_NAME", "Default App Name"));
        //Get the key value from system properties
        System.setProperty("APP_NAME", "App Name1");
        System.out.println("Uses system property app name:" + getKeyValue("APP_NAME", "Default App Name"));
    }

    private static String getKeyValue(String key, String defaultValue) {
        String envKey = System.getenv(key);
        String propKey = System.getProperty(key);
        return IterableUtils.find(Arrays.asList(envKey, propKey, defaultValue), NotNullPredicate.notNullPredicate());
    }

}

In the above code, we first retrieve the key value from environmental variables and also from system properties and create a list contains the envKeyValue, propKeyValue and also a default value. We have to keep the order as is.

Then we use IterableUtils and invoke find method and pass that list and the Not Null predicate. Hence the first not null value would be returned as an output.

** If the key presents in environmental variable then environment value would be returned.

** If the key is not there in environmental variable but present in system properties, then the list looks like this (null, “App Name1”, “Default App Name”). So the first not null value would be returned as an output. So “App Name1” is the output.

** If none of the values exist, then the list looks like this (null, null, “Default App Name”). So the default app name would be returned.

The output of the above program is given below,


Uses default app name:Default App Name
Uses system property app name:App Name1


JAX-RS: REST Streaming Response

In this post, we are going to see how to streaming a response with JAX-RS StreamingOutput.

StreamingOutput is an interface(https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/StreamingOutput.html) and used as a resource method return value or as the entity in a Response when the application wishes to stream the output.

Consider that we have a list of person objects and each object contains first and last name and we want to create a RESTful web service to fetch the person details. Our goal is to stream the response instead of getting everything. Lets see how we can use StreamingOutput to achieve our goal.

The below is Person model class which contains two fields such as first name and last name.



package com.resource;

public class Person {

    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}


The below is the Resource class and the method getDetails passes StreamingOutput to streamPersonData method of PersonService class.

Produces is “application/octet-stream” because we want to save the response as a file instead of rendering that in the browser.


package com.resource;

import com.service.PersonService;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

@Path("/person")
public class PersonResource {

    @GET
    @Produces("application/octet-stream")
    @Path("details")
    public Response getDetails() {
        return Response.ok((StreamingOutput) new PersonService()::streamPersonData).build();
    }

}


The below is the PersonService class which contains the necessary logic to get the person details and convert the person object into JSON format and then write the converted JSON to OutputStream.

Because we are writing the output as JSON array, we are adding a comma symbol at the end of each person JSON output.


package com.service;

import com.model.Person;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class PersonService {

    private ObjectMapper objectMapper = new ObjectMapper();

    public void streamPersonDetails(OutputStream output) throws IOException {
        output.write('[');
        int i = 1;
        List personDetails = getPersonDetails();
        for (Person person : personDetails) {
            output.write(objectMapper.writeValueAsBytes(person));
            if (i < personDetails.size()) {
                output.write(',');
            }
            i++;
        }
        output.write(']');
    }

    private List getPersonDetails() {
        List personList = new ArrayList();
        for (int i = 0; i < 500; i++) {
            Person person = new Person();
            person.setFirstName("Peter:" + i);
            person.setLastName("Woods:" + i);
            personList.add(person);
        }
        return personList;
    }
}


The output is given below,

Streaming_response

If we want to render the response as “JSON” and view the response in browser, then we have to change the produces like this “@Produces(MediaType.APPLICATION_JSON)” and the output look like below,

Streaming_response_JSON