How to Return Multiple Objects from a Java Method

How to return multiple objects from one Java method?

In this instance, I would create an Object Container that holds these two objects and return that object instead.

public class MyContainer
{
List<FixedDeposit> fdList;
List<FDSearchResult> searchList;

public MyContainer()
{

}
}

This is how I would approach this.

How to return multiple objects from a Java Method which are stored in an ArrayList?

I am trying to return all items with the same category name within a list

Using Stream it's pretty easy:

public static List<item> findCategory(List<item> items, String cat) { 
return items.stream()
.filter(item -> item.getcategory().equals(cat))
.collect(Collectors.toList());
}

Java - Best way to return multiple object types from a method

You can either handle this through inheritance, or containment.

You can have Person and DataExporterPerson extend something like AbstractPerson. However, since you have not already done so, then it is probably inappropriate to do inheritance.

I think it was Effective C++ that talked about how containment is better than inheritance. IIRC the reason stated is that containment is more loosely coupled than inheritance.

Here you would have a object that contains both Person and DataExporterPerson. Your method would populate one of those for this union type object, and by seeing which one is null you would know which one you actually have.

public class DBPersonUnion {
private Person person = null;
private DataExporterPerson dataExporterPerson = null;

//getters and setters.
}

How to return multiple defferent objects from a Java method?

You can return a Map<Class, Object> containing the resulting objects' types mapped with their values.

public Map<Class, Object> doSomeStuff(){
Map<Class, Object> map = HashMap<Class, Object>();
map.put(String.getClass(), "This is an example");
map.put(Object.getClass(), new Object());
//...
return map;
}

// You can then retrieve all results by
String stringVal = map.get(String.getClass());
Object objectVal = map.get(Object.getClass());


Related Topics



Leave a reply



Submit