Reputation: 19
I have an ArrayList of a java object with name say, "mylist". I am getting the name of the list(mylist) from database which comes as a String. I need to find the size of this list in JAVA and need to iterate over it.
Is there a way to do this?
Edit: To be more clear here, I have a class "Candidate"
class Candidate {
String firstName;
String lastName;
List<Education>educationRecords;
.....
}
class Education {
String school;
String degree;
.....
}
I need to populate Candidate object from a JSONObject whose structure is very different from Candidate object(so can't use Gson or jackson).
The simple fields like firstName, lastName, school and degree are stored in the database.
I fetch a Listfields and iterate over them to set the Candidate object. For setting firstName, lastName, I am using SpEL.
But, for fields like school and degree, it becomes complex as I would need to know the size of education records in JSONObject.
So, what I thought was while iterating over all fields if school field is present in Education class(using reflection), I would need to check if educationRecords is a of List type in Candidate class and then by some logic X(taking educationRecords as variable name) iterate over it.
It is the logic "X" I am missing.
Upvotes: 1
Views: 148
Reputation: 7798
You can use a map:
Map<String, List> listMap = new Hashmap<>();
Each time you create a list - add it to your map with a key that is a name of your list. Once you get a name you can easily check if such list exists in your map, get it, check its size and iterate through it... Be careful that once you are done with your list you should remove it from your map as well as otherwise you will keep them around and it will eat your memory up.
Upvotes: 0
Reputation: 2199
I don't quite understand the use case here. However, my understanding is that you have an ArrayList<Object> mylist
and you need to find the size of it based on a string retrieved from DB.
You can store the list in a cache, where the key is the name of the list and value is the actual object. You can use redis, eh-cache or memcache (Or anything similar) to achieve the same.
So when you retrieve the name from DB, get the corresponding object from the cache and do size() on the object after type casting it. If your are storing the list type instead of object type in the cache, then the last part is not needed (typecasting).
Upvotes: 1