Gangmax Blog

How to Return Multiple Values from A Java Method

Every Java programmer knows the short answer(and the easiest one) is to create a class with multiple properties each of which is one value that you want to return in the method, and then you return an instance of this class from the method. But in many cases the returned values is just used one time, in such scenarios creating a class is too heavy and unnecessary. In Python, it’s very elegant to return a tuple in such scenarios. But in Java, what is the most elegant way to do it?

I find a answer from here which is to use “Pair<L, R>” which is provided by Apache Common. Code looks like below:

import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.MutablePair;

public Pair<String, Integer> queryById(Integer id) {
Pair<String, Integer> item = new MutablePair<String, Integer>("Zhang", 29);
return item;

In Java this cannot be done from the language level like Python, while can be done from the library level at least.