vegan
vegan

Reputation: 117

How to fix sonarlint warning for one line initialize?

response.setPeopleHealth(new ArrayList<String>() {{
       for(HealthEnum e :HealthEnum.values()) { 
          add(e.getValue());
       }
      }})

sonarlint gives warning for this.

I tried to convert to singletone but it does not work with for, because it cant be added like arraylist.

Can i use lambda or stream?

Upvotes: 3

Views: 260

Answers (1)

Eugene
Eugene

Reputation: 120848

For starters stop using the famous anti-pattern of new ArrayList<String>() {{..., than think about your problem to begin with, you have a array - need a List, thus:

List<String> list = Arrays.stream(HealthEnum.values())
      .map(HealthEnum::getValue)
      .collect(Collectors.toCollection(ArrayList::new));

and pass this ArrayList where you want to, like:

response.setPeopleHealth(list);

Upvotes: 4

Related Questions