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
Java.Net.Connectexception: Connection Refused
How to Check If a File Exists in Java
Access Restriction on Class Due to Restriction on Required Library Rt.Jar
Display Java.Util.Date in a Specific Format
Get Os-Level System Information
Java Error: Comparison Method Violates Its General Contract
How to Determine Day of Week by Passing Specific Date
Why Is Spawning Threads in Java Ee Container Discouraged
Why Does the Default Object.Tostring() Include the Hashcode
How to Make an Executable Jar File
How to Set the Environment Variables For Java in Windows
Java 8 Lambda Function That Throws Exception
What Is the Memory Consumption of an Object in Java
Swing: Link Toggle Buttons Together With a Button Group, Along With Corresponding Menu Items