Hi I have a simple question. I am grabbing data from an API and the way that they have their data setup is that objects have an id and I return it into a list.
So I will get a list of objects like so:
List = {Object1, Object2, Object3, ..., ObjectN};
And these objects will have a parent id like so:
List = {9, 9, 9, 10, 10, 10, 10}
I want to sublist the objects into lists containing the same parent id. What would be a decent algorithm to go about accomplishing this? So something like this:
Object1's parent id is 9
Object2's parent id is 9
Object3's parent id is 9
Object4's parent id is 10
Object5's parent id is 10
Object6's parent id is 10
List<Object> = {Object1, Object2, Object3} // List of all objects with parent id 9
List<Object> = {Object4, Object5, Object6} // List of all objects with parent id 10
I thought about using a HashMap
as well, is that good practice? For scaling purposes I believe that the list of objects will never amount to anything even over the hundreds, or thousands so I don't think speed is necessarily a HUGE issue here.
Background: Language is in Java, and an Object will have parameters like so:
Object: {
parentId:
name:
//etc.
}
Edit: The more I think about this the more I am considering using a sorting algorithm
ANSWER Thanks to SamV:
public HashMap<Integer, List<Object>> createHashMap() {
myHashMap = new HashMap<>();
for (Object object : mObjectList) {
int parentId = object.getParentId();
if (!myHashMap.containsKey(parentId)) {
List<Object> newList = new ArrayList<>();
myHashMap.put(parentId, newList);
}
myHashMap.get(parentId).add(object);
}
return myHashMap;
}
Prior to above and my correct understanding this is a problem that is solved all the time. The pseudo code would go something like this..
fn sortObjects(List objects) {
var sortedParentHashMap = new HashMap();
foreach(object in objects) {
// If the HashMap entry for the current parentId does not exist then initialize
if (!sortedParentHashMap.exists(object.parentId))
// Initialize the entry with a new list
sortedParentHashMap.put(object.parentId, new List());
}
// Now put the object within the specified parentId list
sortedParentHashMap.get(object.parentId).put(object);
}
return sortedParentHashMap();
}
You use the parentId
of each object to perform the sorting for you. You access the entry of that parentId
and add the object to the list. If you have duplicates you could make the new List()
a HashMap to detect duplicates in the same way you would sort via the parentId
.
HashMaps are usually O(1), so the performance should be high.