将一串比特字符串转换成枚举数组,使用 Java 8 流。

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

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

这段代码存在以下问题:

  1. 它使用类型转换从一个 Object 数组转换为一个 Color 数组,可能会导致运行时错误。如果能避免类型转换就更好了。

  2. 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:

  1. It uses type casting to change from an array of Objects to an array of Colors which may create runtime errors. I would like it very much if there was no type casting.

  2. 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 a Color 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.

huangapple
  • 本文由 发表于 2020年4月9日 00:52:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/61105871.html
匿名

发表评论

匿名网友

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

确定