2

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?

1
  • 1
    did you try something? what didn't work? and does shoplists.add(Fruit.Apple.name()) work with your existing code? Commented Jun 30, 2020 at 20:52

3 Answers 3

4

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());
Sign up to request clarification or add additional context in comments.

Comments

3

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());

2 Comments

...or use Arrays.stream(Fruit.values())
or EnumSet.allOf(Fruit.class).stream()
0

Other approach:

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

Comments

Your Answer

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.