首页 > 解决方案 > 在 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 循环和替代方法提出解决方案。

问题:向我推荐什么更快和优化的代码以获得它?

标签: arraysrandomjava-8java-streamshort

解决方案


清晰简单的解决方案:

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是排他性的。


推荐阅读