[英]How to convert if and for each to java Streams
I have an enum class and method getColor
, which returns a color depending on the index or black color when index doesn't exist.我有一个枚举 class 和方法getColor
,它根据索引返回颜色,或者在索引不存在时返回黑色。 I would like to convert this method to Java Streams but I have a problem with how to do it.我想将此方法转换为 Java Streams,但我对如何操作有疑问。
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;
}
You can use the advantage of Optional
:您可以使用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.使用Optional::flatMap
的原因是,如果使用Optional::map
,只要Stream::findFirst
/ Stream::findAny
本身返回Optional
<Optional<Color>>,结果就是Optional<Optional<Color>>
。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.