How to map and assemble a primitive return type using Java 8 Stream

I am new to Java 8 threads, and I am wondering if there is a way to make the call forEach/mapby the method returning byteand accept the intas parameter .

Example:

public class Test {
   private byte[] byteArray; // example of byte array

   public byte getByte(int index) {
      return this.byteArray[index];
   }

   public byte[] getBytes(int... indexes) {
      return Stream.of(indexes)
             .map(this::getByte) // should return byte
             .collect(byte[]::new); // should return byte[]
   }
}

As you can guess, the method getBytesdoes not work. "int[] cannot be converted to int"There is probably no foreach somewhere, but he personally cannot understand it.

However, this works, an old-fashioned approach that I would like to rewrite as Stream.

byte[] byteArray = new byte[indexes.length];
for ( int i = 0; i < byteArray.length; i++ ) {
   byteArray[i] = this.getByte( indexes[i] );
}
return byteArray;
+4
source share
3 answers

You can write your own Collectorand create your own byte[]with ByteArrayOutputStream:

final class MyCollectors {

  private MyCollectors() {}

  public static Collector<Byte, ?, byte[]> toByteArray() {
    return Collector.of(ByteArrayOutputStream::new, ByteArrayOutputStream::write, (baos1, baos2) -> {
      try {
        baos2.writeTo(baos1);
        return baos1;
      } catch (IOException e) {
        throw new UncheckedIOException(e);
      }
    }, ByteArrayOutputStream::toByteArray);
  }
}

And use it:

public byte[] getBytes(int... indexes) {
  return IntStream.of(indexes).mapToObj(this::getByte).collect(MyCollectors.toByteArray());
}
+4

, Eclipse Collections Java. :

public byte[] getBytes(int... indexes) {
    return IntLists.mutable.with(indexes)
            .asLazy()
            .collectByte(this::getByte)
            .toArray();
}

: .

: Eclipse

+5

. , collect, , . :

int[] ints = IntStream.of(indexes)
        .map(this::getByte) // upcast to int, still IntStream
        .toArray(); // specialized collect

IntStream.toArray node , . for.

+3

Source: https://habr.com/ru/post/1679916/


All Articles