如何将 if 和 for each 转换为 Java Streams。

huangapple go评论138阅读模式
英文:

How to convert if and for each to java Streams

问题

我有一个枚举类和方法 getColor,根据索引返回颜色,或在索引不存在时返回黑色。我想将此方法转换为Java Streams,但我不知道如何做。

我的方法:

public static Color getColor(String colorIndex) {
    if (StringUtils.isNotBlank(colorIndex)) {
        int i = Integer.parseInt(colorIndex);
        return Arrays.stream(values())
                .filter(color -> color.colorIndex == i)
                .findFirst()
                .orElse(BLACK);
    }
    return BLACK;
}
英文:

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;
}

答案1

得分: 2

你可以利用Optional的优势:

public static Color getColor(String colorIndex) {

    return Optional.ofNullable(colorIndex)          
        .map(Integer::parseInt)                     
        .flatMap(i -> Arrays.stream(values())       
            .filter(color -> color.colorIndex == i) 
            .findFirst())                           
        .orElse(BLACK);                             
}

使用Optional::flatMap的原因是,如果使用Optional::map,结果将会是Optional<Optional<Color>>,因为Stream::findFirst/Stream::findAny返回的是Optional本身。

英文:

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 -&gt; Arrays.stream(values())       // use the values()
            .filter(color -&gt; color.colorIndex == i) // ... to find a color by the index
            .findFirst())                           // ... as Optional&lt;Color&gt;
        .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&lt;Optional&lt;Color&gt;&gt; as long as Stream::findFirst/Stream::findAny returns Optional itself.

答案2

得分: 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;
    }
}
英文:
public static Color getColor(String colorIndex) {
	if (StringUtils.isNotBlank(colorIndex)) {
		int i = Integer.parseInt(colorIndex);
		Optional&lt;Color&gt; color = values().stream().filter(c -&gt; 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 -&gt; c.colorIndex == i).findAny().orElse(BLACK);
	} catch (NumberFormatException e) {
		return BLACK;
	}
}

huangapple
  • 本文由 发表于 2020年7月23日 18:52:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63052578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定