arrays - 在 Java 8 中生成随机短数组
问题描述
我在一个项目中找到了这段代码:
public static Integer[] getArrayInt(int size, int numBytes) {
return IntStream
.range(0, size)
.mapToObj(time -> {
return extractValue(getArrayByte(numBytes * size), numBytes, time);
}).collect(Collectors.toList()).toArray(new Integer[0]);
}
public static byte[] getArrayByte(int size) {
byte[] theArray = new byte[size];
new Random().nextBytes(theArray);
return theArray;
}
private static int extractValue(byte[] bytesSamples, int numBytes, int time) {
byte[] bytesSingleNumber = Arrays.copyOfRange(bytesSamples, time * numBytes, (time + 1) * numBytes);
int value = numBytesPerSample == 2
? (Byte2IntLit(bytesSingleNumber[0], bytesSingleNumber[1]))
: (byte2intSmpl(bytesSingleNumber[0]));
return value;
}
public static int Byte2IntLit(byte Byte00, byte Byte08) {
return (((Byte08) << 8)
| ((Byte00 & 0xFF)));
}
public static int byte2intSmpl(byte theByte) {
return (short) (((theByte - 128) & 0xFF)
<< 8);
}
如何使用它?
Integer[] coefficients = getArrayInt(4, 2);
输出:
coefficients: [8473, -12817, 12817, -20623]
随机短的这个答案很有吸引力,但它只需要一种方法(正面和负面)。
显然是用流获取随机数组的长代码。
我知道如何使用 for 循环和替代方法提出解决方案。
问题:向我推荐什么更快和优化的代码以获得它?
解决方案
清晰简单的解决方案:
public static Integer[] getArrayInteger(int size) {
return IntStream.generate(()
-> ThreadLocalRandom.current().nextInt(Short.MIN_VALUE, -Short.MIN_VALUE))
.limit(size).boxed().toArray(Integer[]::new);
}
public static Short[] getArrayShort(int size) {
return IntStream.generate(()
-> ThreadLocalRandom.current().nextInt(Short.MIN_VALUE, -Short.MIN_VALUE))
.limit(size).boxed().map(i -> i.shortValue())
.toArray(Short[]::new);
}
-Short.MIN_VALUE
喜欢第二个参数以获得Short.MAX_VALUE
包容性,因为第二个参数 fornextInt
是排他性的。
推荐阅读
- c# - 统一移动鼠标指针到特定方向
- javascript - 反应不关闭对话框
- pygobject - 如何使用 python 创建一个 gedit 插件?
- c++ - MSYS2 MinGW64 在 Windows 上构建 GMP/MPFR 作为静态库,并将它们链接到用 CL 编译的 MSVC 项目中
- android-studio - 运行颤振应用程序时android studio中的gradle错误
- tkinter - 完全删除标签
- python - Keras 中 model.evaluate 和 model.predict 的结果存在差异
- messaging - 如何使用纯 javascript 在 mesibo 中获取特定用户或组的所有消息
- python - python字符串拆分切片并放入列表
- angular - 组中的自定义 ag-grid 单元格