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
Objects to an array ofColors 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
mapToObjto 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 aColorobject.
map(i -> i.toArray[i])?