Skip to content
Advertisement

Return all possible combinations of two custom type lists in java

I am trying to add the values of ingredients and topping to my scoops list, but that doesn’t work due to the type of scoops. I can’t change the type of scoops to String and I need to solve the problem as it is in the code below. See the picture to see the problem I get when I try to add values to the list.

import java.util.ArrayList;
import java.util.List;

import static java.lang.Math.abs;

public class IceCreamMachine {
    public String[] ingredients;
    public String[] toppings;

    public static class IceCream {
        public String ingredient;
        public String topping;

        public IceCream(String ingredient, String topping) {
            this.ingredient = ingredient;
            this.topping = topping;
        }
    }

    public IceCreamMachine(String[] ingredeints, String[] toppings) {
        this.ingredients = ingredeints;
        this.toppings = toppings;
    }

    public List<IceCream> scoops() {
        List<IceCream> scoops = new ArrayList<>();
        
        for (int j = 0; j<ingredients.length;j++){
            for(int l = 0; l<toppings.length;l++){
                scoops.add(ingredients[j]+", "+toppings[l]);
            }
        }
        return scoops;
    }

    public static void main(String[] args) {
        IceCreamMachine machine = new IceCreamMachine(new String[]{
                "vanilla", "chocolate"
        }, new String[]{
                "chocolate sauce"
        });
        List<IceCream> scoops = machine.scoops();

        /*
         * Should print:
         * vanilla, chocolate sauce
         * chocolate, chocolate sauce
         */
        for (IceCream iceCream : scoops) {
            System.out.println(iceCream.ingredient + ", " + iceCream.topping);
        }
    }
}

Advertisement

Answer

You are very close. One line to change.

scoops.add(new IceCream(ingredients[j],toppings[l]));

instead of

scoops.add(ingredients[j]+", "+toppings[l]);

You need a ‘full’ IceCream object to add to the scoops object. But your code constructed a description as a String.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement