jeudi 21 mai 2020

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?




Aucun commentaire:

Enregistrer un commentaire