How to Return Multiple Values in Java

Posted by Marta on December 18, 2020 Viewed 1011 times

Learn how to return multiple values in java. There are three main ways to return multiple values. This tutorial include code examples and explanations.

Card image cap

Hey there! In this tutorial, you will learn how to return multiple values in java. There are three main ways to return multiple values.

Return Custom Object

You can create a wrapper class that contains all the values your method should return. This way will fit if you need to return more than two values of different types. See this in action below:

public class Sample {

    public Bundle calculateSomething(){
        // some calculations here
        Bundle result = new Bundle();
        result.value1 = "3";
        result.value2 = "Hey";
        result.value3 = 3;
        return result;
    }

    class Bundle{
        public String value1;
        public String value2;
        public int value3;
    }
}

The method calculateSomething() will return 3 values: value1, value2 and value3, each value can be of a different type.

I will recommend using encapsulation; in other words, mark the fields as private and create a getter method to access every field. In this case, I have declared the fields as public just for simplicity.

Return a Map

Another solution to how to return multiples values in java is producing a map. This solution will be appropriate if all values to return are of the same type. See below how this will work:

import java.util.HashMap;
import java.util.Map;

public class Sample {

    public Map<String, Integer> anotherCalculation(){
        // some calculations here
        Map<String, Integer> result = new HashMap<>();
        result.put("average",20);
        result.put("max", 50);
        result.put("min", 34);
        return result;
    }

}

See below how to use the method created above to return multiple values:

Sample s = new Sample();
Map<String,Integer> results = s.anotherCalculation();
Integer averageResult = results.get("average");

Why returning a Map and not other collections, such as a List? In case all values to return are of the same type, we could use other collection, such as List, Array, etc. However, it will be challenging to identify the values. Using a map allows you to assign a label to each value. Therefore you could retrieve values out of the Map using this label.

Return a Pair

Lastly, another possible solution is returning a Pair. This solution is only suitable if you need to return two values. Otherwise, one of the solutions above will be a better fit. See a code example of how to create and return a pair:

import javafx.util.Pair;

public class Sample {

    public Pair<Long,Long> moreCalculation(){
        // some calculations
        return new Pair<>(3L,45L);
    }

}

You can access the Pair values using the methods getKey() and getValue(). See this in action below:

Sample s = new Sample();
Pair<Long,Long> results = s.moreCalculation();
Long firstResult = results.getKey();
Long secondResult = results.getValue();

Conclusion

To summarise, in this tutorial, we have seen how to return multiple values in java. In case you like to return multiples values of different types, the best option is returning a custom class. In case the values you want to return aren’t all the same type, returning a Map will fit well. And finally, you could produce a Pair if you only need to return two values.

I hope this tutorial was useful, and thank you so much for reading and supporting this blog. Happy Coding!

More interesting articles

Runnable vs Callable – Find out the differences

What is a mutator method in Java?

How to Write a Tic Tac Toe Game in Java using classes

Java 8 Cheat Sheet – Most Used Conversions – Char To String

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java