0

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).

asked Nov 12, 2013 at 18:38

1 Answer 1

1

Generics aren't the answer here, because all your data objects are ZooEntity objects. If you had related classes such as Animal, Vegetable and Mineral it would make sense to have a generic method dealing with "something that has an ID", but that's not the case here.

What you do have is things, collections of things and nested collections of things. There is no natural interface that you could use or define to do the job at hand with one function - collections simply don't have a getId() method. You could simplify your code using recursion, but that would mean instanceof checks at every level of processing. As long as you only have linear lists and singly-nested lists, the most obvious route is simply to have your second method call the first one.

answered Nov 12, 2013 at 19:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.