How to fix sonarlint warning for one line initialize?

Viewed 133
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?

1 Answers

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