Get entities ids from two similar collections using one method
- by Patryk Roszczyniala
I've got two lists:
List<Integer, ZooEntity> zoos;
List<Integer, List<ZooEntity>> groupOfZoos;
These operations will return collections of values:
Collection<ZooEntity> cz = zoos.values();
Collection<List<ZooEntity>> czList = groupOfZoos.values();
What I want to achieve is to get list of all zoo ids.
List<Integer> zooIds = cz ids + czList ids;
Of course I can create two methods to do what I want:
public List<Integer> getIdsFromFlatList(Collection<ZooEntity> list) {
List<Integer> ids = new ArrayList<Integer>();
for (ZooEntity z : list) {
ids.add(z.getId());
}
return ids;
}
public List<Integer> getIdsFromNestedList(Collection<List<ZooEntity>> list) {
List<Integer> ids = new ArrayList<Integer>();
for (List<ZooEntity> zList : list) {
for (ZooEntity z : zList) {
ids.add(z.getId());
}
}
return ids;
}
As you can see those two methods are very similar and here is my question:
Is it good to create one method (for example using generics) which will get ids from those two lists (zoos and groupOfZoos). If yes how it should look like? If no what is the best solution?
BTW. This is only the example. I've got very similar problem at job and I want to do it in preety way (I can't change enities, I can change only getIds...() methods).