Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.