How to return 2 values from a Java method?
There are a few ways you can return multiple values from a Java method:
- Return an array: You can create an array that contains the values you want to return, and then return the array. For example:
public static int[] getValues() {
return new int[] {1, 2};
}
// usage:
int[] values = getValues();
- Return a custom object: You can create a custom object that contains the values you want to return, and then return an instance of that object. For example:
public class Values {
private int value1;
private int value2;
public Values(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
// getters and setters
}
public static Values getValues() {
return new Values(1, 2);
}
// usage:
Values values = getValues();
- Use a third-party library: There are several third-party libraries that allow you to return multiple values from a method. One example is the Google Guava library, which provides the
Pair
class that you can use to return a pair of values. For example:
import com.google.common.collect.Pair;
public static Pair<Integer, Integer> getValues() {
return Pair.of(1, 2);
}
// usage:
Pair<Integer, Integer> values = getValues();
int value1 = values.getLeft();
int value2 = values.getRight();
- Use a Java 8 lambda expression: If you are using Java 8 or higher, you can use a lambda expression to return multiple values. For example:
@FunctionalInterface
public interface ValueSupplier {
int[] get();
}
public static void getValues(ValueSupplier supplier) {
int[] values = supplier.get();
}
// usage:
getValues(() -> new int[] {1, 2});