在Java 8中生成随机短数组

问题描述 投票:0回答:1

我在一个项目中发现了这段代码。

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循环和替代方法。

我知道如何提出一个解决方案,用for循环和替代方法。

问题: 有什么更快更优化的代码来获得它推荐给我?

arrays random java-8 java-stream short
1个回答
0
投票

清楚而简单的解决方案。

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 包容性,因为第二个论点 nextInt 是外延的。

© www.soinside.com 2019 - 2024. All rights reserved.