Java8: Create list of object using enum value

Viewed 729

I have a list of enum like this :

public enum Fruit {
   Apple,
   Mango,
   Banana,
   kiwi
}

and I have class like this

public class FruitShop {
    private String name;

    public FruitShop(String name) {
       this.name = name
}

I want to create a list of object of FruitShop class passing each enum as an arument

List<FruitShop> shoplists = new new ArrayList<>()
shoplists.add(Fruit.Apple.name())
shoplists.add(Fruit.Mango.name())
shoplists.add(Fruit.Banana.name())
shoplists.add(Fruit.kiwi.name())

How can I achieve this using java8 stream?

3 Answers

You can use EnumSet with stream like this:

List<FruitShop> shoplists = EnumSet.allOf(Fruit.class).stream()
        .map(f -> new FruitShop(f.name()))
        .collect(Collectors.toList());

You can use Fruit.values() then map to create FruitShop and collect as list

List<FruitShop> shoplists = Stream.of(Fruit.values())
                                  .map(f -> new FruitShop(f.name()))
                                  .collect(Collectors.toList());

Other approach:

Arrays.stream(Fruit.values())
        .map(Fruit::name)
        .map(FruitShop::new)
        .collect(Collectors.toList());
Related