Return Multiple values in Java
In Java, there are multiple ways to return multiple values from a method. Returning multiple values means that a method can provide more than one piece of information as its result. Normally, a method in Java can only return a single value of a specific type. However, there are scenarios where you may need to retrieve and use multiple values from a method call.
Approach: Using an Array
We can create an array to store multiple values and return them from the method:
FileName: CalculationExample.java
public class CalculationExample { public static int[] calculate(int a, int b) { // method signature that takes two integer arguments and returns an integer array int sum = a + b; // calculates the sum of a and b int difference = a - b; // calculates the difference between a and b int[] result = {sum, difference}; // creates an array with the calculated values return result; // returns the array } public static void main(String[] args) { int a = 5; // initializes a int b = 3; // initializes b int[] result = calculate(a, b); // calls the calculate method and stores the returned array System.out.println("Sum: " + result[0]); // prints the sum System.out.println("Difference: " + result[1]); // prints the difference } }
Output:
Sum: 8 Difference: 2
Approach: Using a Class
We can create a class to store multiple values and return an object of that class from the method. For example:
FileName: MultipleValuesExample.java
public class MultipleValuesExample { // Define a method that returns multiple values using an object of a custom class public static CalculationResult calculate(int a, int b) { // Calculate the sum and difference of the two input integers int sum = a + b; int difference = a - b; // Create a new instance of CalculationResult class and set its fields to the calculated values CalculationResult result = new CalculationResult(); result.sum = sum; result.difference = difference; // Return the instance of CalculationResult class return result; } // Define a main method to test the calculate() method public static void main(String[] args) { // Define two input integers int a = 5; int b = 3; // Call the calculate() method to get the sum and difference of the two input integers CalculationResult result = calculate(a, b); // Print the sum and difference of the two input integers using the fields of the returned CalculationResult instance System.out.println("Sum: " + result.sum); System.out.println("Difference: " + result.difference); } } // Define a custom class to hold the result of the calculation class CalculationResult { int sum; int difference; }
Output:
Sum: 8 Difference: 2
Approach: Using a Map
We can use a Map to store key-value pairs of multiple values and return the Map object from the method. Here's an example:
FileName: MapExample.java
import java.util.HashMap; import java.util.Map; public class MapExample { // This method takes two integers as arguments, calculates their sum and difference, // and returns a Map object with "sum" and "difference" keys and the corresponding values public static Map<String, Integer> calculate(int a, int b) { int sum = a + b; int difference = a - b; // Create a new HashMap object to hold the calculated values Map<String, Integer> result = new HashMap<>(); // Add the calculated values to the HashMap result.put("sum", sum); result.put("difference", difference); // Return the HashMap return result; } // This is a sample main method to demonstrate how to use the calculate() method public static void main(String[] args) { int a = 10; int b = 5; // Call the calculate() method and store the returned Map object in a variable Map<String, Integer> result = calculate(a, b); // Retrieve the values from the Map using the keys int sum = result.get("sum"); int difference = result.get("difference"); // Print the results System.out.println("The sum of " + a + " and " + b + " is " + sum); System.out.println("The difference of " + a + " and " + b + " is " + difference); } }
Output:
The sum of 10 and 5 is 15 The difference of 10 and 5 is 5
Approach: Using a Tuple
We can use a Tuple, which is an object that can hold multiple values of different types, and return the Tuple object from the method. Tuple to hold multiple values and return the Tuple from the method. A Tuple is a fixed-sized sequence of elements, typically used to group together related values. There are many Tuple implementations available in Java, such as the Pair class from Apache Commons.
FileName: PairExample.java
import org.javatuples.Pair; public class PairExample { // This method takes two integers as arguments, calculates their sum and difference, // and returns a Pair object with the corresponding values public static Pair<Integer, Integer> calculate(int a, int b) { int sum = a + b; int difference = a - b; // Create a new Pair object to hold the calculated values Pair<Integer, Integer> result = Pair.with(sum, difference); // Return the Pair return result; } // This is a sample main method to demonstrate how to use the calculate() method public static void main(String[] args) { int a = 10; int b = 5; // Call the calculate() method and store the returned Pair object in a variable Pair<Integer, Integer> result = calculate(a, b); // Retrieve the values from the Pair using its methods int sum = result.getValue0(); int difference = result.getValue1(); // Print the results System.out.println("The sum of " + a + " and " + b + " is " + sum); System.out.println("The difference of " + a + " and " + b + " is " + difference); } }
Output:
The sum of 10 and 5 is 15 The difference of 10 and 5 is 5
Approach: Using an Object Array
We can use an Object array to store multiple values of different types and return the array from the method. Here's an example:
FileName: Calculation.java
public class Calculation { // This method takes two integers as input and returns an array of objects // containing the sum and difference of the two integers. public static Object[] calculate(int a, int b) { int sum = a + b; int difference = a - b; Object[] result = {sum, difference}; return result; } // It is the main method of the program, which calls the calculate method // with two integers and prints the results. public static void main(String[] args) { int a = 10; int b = 5; Object[] result = calculate(a, b); System.out.println("Sum: " + result[0]); System.out.println("Difference: " + result[1]); } }
Output:
Sum: 15 Difference: 5
Approach: Using a Java Collection
We can return a Java Collection, such as List or Map, to hold the multiple values. For example:
FileName: MultipleValues.java
import java.util.ArrayList; import java.util.List; public class MultipleValues { // Returns a List of Integer values. //return List of Integer values. public static List<Integer> getValues() { List<Integer> values = new ArrayList<>(); values.add(1); values.add(2); values.add(3); return values; } //Main method to demonstrate the usage of getValues() method. public static void main(String[] args) { List<Integer> values = getValues(); System.out.println("Values: " + values); } }
Output:
Values: [1, 2, 3]
Approach: Using Java 8 Streams
You can use Java 8 Streams to return multiple values.
For example:
FileName: MultipleValues.java
import java.util.stream.Stream; public class MultipleValues { // Returns a stream of integer values. //return Stream of integer values. public static Stream<Integer> getValues() { return Stream.of(1, 2, 3); } // Main method to demonstrate the usage of getValues() method. //param args Command-line arguments. public static void main(String[] args) { Stream<Integer> values = getValues(); values.forEach(System.out::println); } }
Output: 1 2 3
Approach: Using a custom class with multiple return methods
We can create a custom class with multiple methods that return individual values, and return an instance of the class from the method. For example:
FileName: Main.java
// A custom class to hold multiple values public class Values { private int value1; private int value2; private int value3; // Constructor to set the values public Values(int value1, int value2, int value3) { this.value1 = value1; this.value2 = value2; this.value3 = value3; } public class Main { public static void main(String[] args) { // Get the values using the custom class Values values = getValues(); // Print the individual values System.out.println("Value 1: " + values.getValue1()); System.out.println("Value 2: " + values.getValue2()); System.out.println("Value 3: " + values.getValue3()); } // Method to return an instance of the custom class with the values public static Values getValues() { Values values = new Values(1, 2, 3); return values; } }
Output:
Value 1: 1 Value 2: 2 Value 3: 3