0

I have an enum class and method getColor, which returns a color depending on the index or black color when index doesn't exist. I would like to convert this method to Java Streams but I have a problem with how to do it.

My method:

public static Color getColor(String colorIndex) {
    if (StringUtils.isNotBlank(colorIndex)) {
        int i = Integer.parseInt(colorIndex);
        for (Color color : values()) {
            if (color.colorIndex == i) {
                return color;
            }
        }
    }
    return BLACK;
}
Naman
  • 27,789
  • 26
  • 218
  • 353
Hubu999
  • 73
  • 2
  • 9
  • for `foreach` part you can use `findFirst()` [Find first element by predicate](https://stackoverflow.com/questions/23696317/find-first-element-by-predicate) – Eklavya Jul 23 '20 at 10:58

2 Answers2

2

You can use the advantage of Optional:

public static Color getColor(String colorIndex) {

    return Optional.ofNullable(colorIndex)          // Optional colorIndex
        .map(Integer::parseInt)                     // as int
        .flatMap(i -> Arrays.stream(values())       // use the values()
            .filter(color -> color.colorIndex == i) // ... to find a color by the index
            .findFirst())                           // ... as Optional<Color>
        .orElse(BLACK);                             // if noone of the above, then BLACK
}

The reason of using Optional::flatMap is if Optional::map would be used, the result would be Optional<Optional<Color>> as long as Stream::findFirst/Stream::findAny returns Optional itself.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0
public static Color getColor(String colorIndex) {
    if (StringUtils.isNotBlank(colorIndex)) {
        int i = Integer.parseInt(colorIndex);
        Optional<Color> color = values().stream().filter(c -> c.colorIndex == i).findAny();
        if (color.isPresent())
            return color.get();
    }
    return BLACK;
}

Or

public static Color getColor(String colorIndex) {
    try {
        int i = Integer.parseInt(colorIndex);
        return values().stream().filter(c -> c.colorIndex == i).findAny().orElse(BLACK);
    } catch (NumberFormatException e) {
        return BLACK;
    }
}
unrated
  • 252
  • 4
  • 22
  • I try to use your second idea and I have two error, first in .stream() (Cannot resolve method 'stream' in 'Color') and second in c.colorIndex (Cannot resolve symbol 'colorIndex'). – Hubu999 Jul 23 '20 at 12:07