How to return multiple objects from a Java method?

java return multiple values from method
java return multiple values of different types
java 8 return multiple values
how to return multiple arrays from a method in java
how to store multiple values in a variable in java
java multiple return statements
how to return an array in java
java have method return two values

I want to return two objects from a Java method and was wondering what could be a good way of doing so?

The possible ways I can think of are: return a HashMap (since the two Objects are related) or return an ArrayList of Object objects.

To be more precise, the two objects I want to return are (a) List of objects and (b) comma separated names of the same.

I want to return these two Objects from one method because I dont want to iterate through the list of objects to get the comma separated names (which I can do in the same loop in this method).

Somehow, returning a HashMap does not look a very elegant way of doing so.

If you want to return two objects you usually want to return a single object that encapsulates the two objects instead.

You could return a List of NamedObject objects like this:

public class NamedObject<T> {
  public final String name;
  public final T object;

  public NamedObject(String name, T object) {
    this.name = name;
    this.object = object;
  }
}

Then you can easily return a List<NamedObject<WhateverTypeYouWant>>.

Also: Why would you want to return a comma-separated list of names instead of a List<String>? Or better yet, return a Map<String,TheObjectType> with the keys being the names and the values the objects (unless your objects have specified order, in which case a NavigableMap might be what you want.

How to return multiple objects from a Java method?, Return multiple values from a method in Java 8. public static void We can encapsulate all returned types into a class and then return an object of that class. If it's always going to be 2 objects of that type, create another object to store them both and return that. – Steve Smith Feb 28 '17 at 10:35 The types are not same, fdList - list and sum is not a list – Shantha Feb 28 '17 at 10:40

Returning Multiple values in Java, Yes, we can return multiple objects from a method in Java as the method always encapsulates the objects and then returns. You can return a  Yes, we can return multiple objects from a method in Java as the method always encapsulates the objects and then returns. You can return a list of objects like: public class CustomObject<Obj> { public final int id; public final Obj customObject; public CustomObject(int id,Obj customObject) { this.id = id; this.customObject = customObject; }}

In the event the method you're calling is private, or called from one location, try

return new Object[]{value1, value2};

The caller looks like:

Object[] temp=myMethod(parameters);
Type1 value1=(Type1)temp[0];  //For code clarity: temp[0] is not descriptive
Type2 value2=(Type2)temp[1];

The Pair example by David Hanak has no syntactic benefit, and is limited to two values.

return new Pair<Type1,Type2>(value1, value2);

And the caller looks like:

Pair<Type1, Type2> temp=myMethod(parameters);
Type1 value1=temp.a;  //For code clarity: temp.a is not descriptive
Type2 value2=temp.b;

How to return multiple objects from a Java method?, Then, we need to return that most distant Coordinate object, along with the distance. Let's first create a generic two-fields tuple: ? 1. 2. 3. Java doesn’t support multi-value returns. We can use following solutions to return multiple values. If all returned elements are of same type

You may use any of following ways:

private static final int RETURN_COUNT = 2;
private static final int VALUE_A = 0;
private static final int VALUE_B = 1;
private static final String A = "a";
private static final String B = "b";

1) Using Array

private static String[] methodWithArrayResult() {
    //...
    return new String[]{"valueA", "valueB"};
}

private static void usingArrayResultTest() {
    String[] result = methodWithArrayResult();
    System.out.println();
    System.out.println("A = " + result[VALUE_A]);
    System.out.println("B = " + result[VALUE_B]);
}

2) Using ArrayList

private static List<String> methodWithListResult() {
    //...
    return Arrays.asList("valueA", "valueB");
}

private static void usingListResultTest() {
    List<String> result = methodWithListResult();
    System.out.println();
    System.out.println("A = " + result.get(VALUE_A));
    System.out.println("B = " + result.get(VALUE_B));
}

3) Using HashMap

private static Map<String, String> methodWithMapResult() {
    Map<String, String> result = new HashMap<>(RETURN_COUNT);
    result.put(A, "valueA");
    result.put(B, "valueB");
    //...
    return result;
}

private static void usingMapResultTest() {
    Map<String, String> result = methodWithMapResult();
    System.out.println();
    System.out.println("A = " + result.get(A));
    System.out.println("B = " + result.get(B));
}

4) Using your custom container class

private static class MyContainer<M,N> {
    private final M first;
    private final N second;

    public MyContainer(M first, N second) {
        this.first = first;
        this.second = second;
    }

    public M getFirst() {
        return first;
    }

    public N getSecond() {
        return second;
    }

    // + hashcode, equals, toString if need
}

private static MyContainer<String, String> methodWithContainerResult() {
    //...
    return new MyContainer("valueA", "valueB");
}

private static void usingContainerResultTest() {
    MyContainer<String, String> result = methodWithContainerResult();
    System.out.println();
    System.out.println("A = " + result.getFirst());
    System.out.println("B = " + result.getSecond());
}

5) Using AbstractMap.simpleEntry

private static AbstractMap.SimpleEntry<String, String> methodWithAbstractMapSimpleEntryResult() {
    //...
    return new AbstractMap.SimpleEntry<>("valueA", "valueB");
}

private static void usingAbstractMapSimpleResultTest() {
    AbstractMap.SimpleEntry<String, String> result = methodWithAbstractMapSimpleEntryResult();
    System.out.println();
    System.out.println("A = " + result.getKey());
    System.out.println("B = " + result.getValue());
}

6) Using Pair of Apache Commons

private static Pair<String, String> methodWithPairResult() {
    //...
    return new ImmutablePair<>("valueA", "valueB");
}

private static void usingPairResultTest() {
    Pair<String, String> result = methodWithPairResult();
    System.out.println();
    System.out.println("A = " + result.getKey());
    System.out.println("B = " + result.getValue());
}

How to Return Multiple Values From a Java Method, In this post, we will see how to return multiple values from a function in Java Below is simpler version of above program that uses an Object array to store all  How to Return Object from a Method in JAVA. A method returns to the code that invoked it when it: Completes all the statements in the method. Reaches a return statement. or Throws an exception (covered later) Whichever occurs first between the last two.

I almost always end up defining n-Tuple classes when I code in Java. For instance:

public class Tuple2<T1,T2> {
  private T1 f1;
  private T2 f2;
  public Tuple2(T1 f1, T2 f2) {
    this.f1 = f1; this.f2 = f2;
  }
  public T1 getF1() {return f1;}
  public T2 getF2() {return f2;}
}

I know it's a bit ugly, but it works, and you just have to define your tuple types once. Tuples are something Java really lacks.

EDIT: David Hanak's example is more elegant, as it avoids defining getters and still keeps the object immutable.

5 ways to Return multiple values from a method in Java, How can I return two objects from a method in Java? Returning Objects. In java, a method can return any type of data, including objects. For example, in the following program, the incrByTen ( ) method returns an object in which the value of a (an integer variable) is ten greater than it is in the invoking object. filter_none.

Return more than one variable from Java method, How can I return more than one value from a method in Java? In this tutorial we will learn how to return object of a class from a method in Java programming language. In the previous tutorial we learned how to pass an object as argument to a method . Now, lets go ahead and create a class that will return an object.

Why Many Return Statements Are a Bad Idea in OOP, and that's it. Instead, there are objects of class If and GreaterThan . You can return only one value in Java. If needed you can return multiple values using array or an object. Example. In the example given below the calculate() method accepts two integer variables performs the addition subtraction, multiplication and, division operations on them stores the results in an array and returns the array.

Returning Objects Questions and Answers, You can return only one value in Java. If needed you can return multiple values using array or an object. Example In the example given below  Multiple return values. A method is called. It returns 3 values—2 ints and a String. In Java we must use a class instance, an array or other collection to return these values.

Comments
  • Is the List and the CSVs basically diffent views of the same data? It sounds like what you need is an Object where you have a single List reference and a sort of lookup table.
  • Related question: stackoverflow.com/questions/53453058/…
  • The reason for returning comma separated list is: If I dont create the list here, I would have to do this in the caller by looping through the objects (CS value is needed). Perhaps, I am pre-optimizing unnecessarily.
  • I've always wondered why Java doesn't have a Pair<T, U> class for this reason.
  • Jagmal: yes, if the only rason for returning the comma-separated list is this optimization, then forget about it.
  • This only works well if the items you'd like to return are of the same class, or at least have a close common ancestor. I mean, using Object in place of WhateverTypeYouWant isn't very neat.
  • @David: I agree that using Object here isn't very neat, but then again return objects without any common ancestor (except Object of course) isn't very neat as well. I'd even say it's a code smell, if you need that.
  • I usually have this class knocking about in each codebase I work on. I'd also add: a hashCode/equals implementation, and possibly a static isInstance() and cast() method.
  • Sure, there are many ways to make this class smarter and more convenient to use. The version above includes what's just enough in a one-shot declaration.
  • @jamesh: do you mind to write your Pair in full details here? I'd like to know how it looks like after supplying "a hashCode/equals implementation, and possibly a static isInstance() and cast() method." Thank you.
  • @QiangLi - I usually generate the hashcode & equals methods. Instance method isInstance takes two classes and makes sure that the instance's a & b are instances of those classes. Cast takes a Pair<?,?> and carefully casts it to a Pair<A,B>. The implementations should be fairly easy (hint: Class.cast(), Class.isInstance())
  • That's a very nice Pair implementation. One minor change I'd make: add a message to the ClassCastException. Otherwise debugging becomes a nightmare if this fails for some reason. (and the rawtypes suppress-warnings would be unnecessary if you'd cast to Pair<?,?> (which works, because you only need Object methods from a and b). Do you mind if I tweak the code?