英文:
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 -> 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.
答案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<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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论