Search code examples
arraysrandomjava-8java-streamshort

generate Array of random short in Java 8


I found this code in a project:

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

How to use it?

Integer[] coefficients = getArrayInt(4, 2);

The output:

coefficients: [8473, -12817, 12817, -20623]

This answer for random short is attractive, but it needs both (positive and negative) in only one method).

Obviously is a long code for obtain the Array of Random short with stream.

I know how to present a solution, with for loop and alternative method.

The Question: What faster and optimized code in order to obtain it recommend to me?


Solution

  • clear and simple solution:

    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 like second argument in order to obtain Short.MAX_VALUE inclusive because the second argument for nextInt is exlusive.