英文:
Convert a String of bits into an array of enums using java 8 streams
问题
这是枚举类部分:
enum Color { RED, GREEN }
以下是转换代码部分:
Color[] colors = Arrays.stream(sc.nextLine().split("\\s"))
.map(i -> {
if (i.equals("0")) return Color.RED;
else return Color.GREEN;
})
.toArray(Color[]::new);
这段代码存在以下问题:
-
它使用类型转换从一个
Object
数组转换为一个Color
数组,可能会导致运行时错误。如果能避免类型转换就更好了。 -
map
函数。我在 StackOverflow 上搜索了mapToObj
,看是否有办法指定map
的返回类型。我认为当你指定map
应该返回一个Color
对象时会更安全。
英文:
I have a string of space separated bits (1's and 0's) that I want to convert to an array of enums. Below is my effort so far.
This is the Enum class
enum Color { RED, GREEN }
Here is the conversion code.
Color[] colors = (Color[]) Arrays.stream(sc.nextLine().split("\\s"))
.map(i -> {
if (i.equals("0")) return Color.RED;
else return Color.GREEN;
})
.toArray();
I am facing the following problems with this code:
-
It uses type casting to change from an array of
Object
s to an array ofColor
s which may create runtime errors. I would like it very much if there was no type casting. -
The map function. I have searched here on StackOverflow on
mapToObj
to see if there is a way I can specify the return type of the map. I think it is safer when you specify that the map should return aColor
object.
答案1
得分: 4
为了避免类型转换,请将参数传递给 toArray
:
.toArray(Color[]::new)
这是唯一需要的更改。
对于映射函数,不需要指定返回类型。由于您只返回 Color
的实例,因此其返回类型是 Color
。
英文:
To avoid the casting, pass parameter to toArray
:
.toArray(Color[]::new)
This is the only change required.
There is no need to specify a return type for the map function. The fact that you're returning only instances of Color
means its return type is Color
.
答案2
得分: 2
这是正确的方法:
Color[] colors = Arrays.stream(sc.nextLine().split(" "))
.map(i -> i.equals("0") ? Color.RED : Color.GREEN)
.toArray(Color[]::new);
如果你想将 Stream
转换为对象数组,你需要使用 Stream::toArray(IntFunction)
方法。
英文:
This is the way to go:
Color[] colors = Arrays.stream(sc.nextLine().split("\\s"))
.map(i -> i.equals("0") ? Color.RED : Color.GREEN)
.toArray(Color[]::new);
If you want to convert a Stream
to an object array, you need to use Stream::toArray(IntFunction)
method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论