TheOnlyWAR10CK93
TheOnlyWAR10CK93

Reputation: 113

Java - Sorting out subclass from ArrayList of superclass

I have an ArrayList which contains objects of the super class and some subclass objects. Let's call them subclass1 and subclass2.

Is there a way I can go ArrayList and discern which objects are SuperClass, subclass1 and subclass2. So I can put them into ArrayList and ArrayList.

This is an overly simplified version but it demonstrates what I'm hoping to do.

    public class food{
    private String name;
    public food(String name){
        this.name = name;
    }
}   

public class pudding extends food{
    public pudding(String name){
        super(name);
    }
}

public class breakfast extends food{
    public breakfast(String name){
        super(name);
    }
}

public static void main(String args[]){
    ArrayList<food> foods = new ArrayList();

    foods.add(new food("Sausage"));
    foods.add(new food("Bacon"));
    foods.add(new pudding("cake"));
    foods.add(new breakfast("toast"));
    foods.add(new pudding("sponge"));
    foods.add(new food("Rice"));
    foods.add(new breakfast("eggs"));

    ArrayList<pudding> puds = new ArrayList();
    ArrayList<breakfast> wakeupjuices = new ArrayList();

    for(food f : foods){
        //if(f is pudding){puds.add(f);}
        //else if(f is breakfast){wakeupjuices.add(f);}
    }

}

Upvotes: 1

Views: 1044

Answers (2)

Fritz Duchardt
Fritz Duchardt

Reputation: 11920

This can be solved elegantly with Guava using Multimaps.index:

    Function<food, String> filterFood = new Function<food, String>() {
        @Override
        public String apply(food input) {

            if (input instanceof pudding) {
                return "puddings";
            }
            if (input.b instanceof breakfast) {
                return "breakfasts";
            }
            return "something else";
        }
    };

    ImmutableListMultimap<String, food> separatedFoods = Multimaps.index(list, filterFood);

The output will be a Guava Multimap with three separate entries for:

  1. an immutable list with all breakfast instances under key "breakfasts".
  2. an immutable list with all pudding instances under key "puddings".
  3. and possibly an immutable list with objects with every food instance that is neither breakfast nor pudding under key "something else".

Upvotes: 0

BluesSolo
BluesSolo

Reputation: 608

You can check for the desired types like this, using the instanceof keyword:

for (food f : foods)
{
    if (f instanceof pudding)
        puds.add(f);
    else if (f instanceof breakfast)
        wakeupjuices.add(f);
}

Upvotes: 2

Related Questions