-1

Java 8 introduced Arrays.stream() to convert a (primitive) array to a Stream.

How can this method be used to get a stream for a byte[]?


It looks like the method only exists for double[], int[] and long[], but not for byte[].

Arrays.stream() methods

I guess the reason is that Arrays.stream() internally utilizes StreamSupport which does not provide a method for byte[] ...

Stefan
  • 171
  • 1
  • 13
  • Interesting related SO question: "Why are new java.util.Arrays methods in Java 8 not overloaded for all the primitive types?" https://stackoverflow.com/q/22918847/1518225 – Stefan Nov 03 '22 at 15:13

4 Answers4

2

You can create an IntStream using map

byte[] bytes = ...;
IntStream byteStream = IntStream.range(0, bytes.length).map(i -> bytes[i]);
MikeFHay
  • 8,562
  • 4
  • 31
  • 52
2

You could also do it like this. Index the array via an IntStream and then return a boolean depending on the presence of the value.

boolean v = IntStream.range(0, demoArray.length).map(i -> demoArray[i])
    .filter(i -> i == 0x42).findFirst().isPresent();

System.out.println(v);

prints

true

Or as Youcef Laidani kindly pointed out use anyMatch.

boolean v = IntStream.range(0, demoArray.length).map(i -> demoArray[i])
    .anyMatch(i -> i == 0x42);
Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
WJS
  • 36,363
  • 4
  • 24
  • 39
  • 2
    …and even shorter `boolean v = IntStream.range(0, demoArray.length) .anyMatch(i -> demoArray[i] == 0x42);` – Holger Nov 04 '22 at 11:37
1

Since I needed the byte[] stream only for anyMatch(), I came up with the following snippet as "quick fix":

private static boolean anyMatch(byte[] data, Predicate<Byte> predicate) {
  for(byte d : data) {
     if(predicate.test(d)) {
      return true;
    }
  }
  return false;
}

To be called like this:

byte[] demoArray new byte[]{0x1, 0x2, 0x42};
boolean exists = anyMatch(demoArray, i -> i == 0x42);
Stefan
  • 171
  • 1
  • 13
0

Well, you still can do Arrays.stream on Objects of type T

so all you need to do is converting byte[] into Byte[].

To convert byte[] into Byte[] you basically need to do foreach loop and convert each byte into Byte or you can use apache lang3 utils

byte[] byteArray = new byte[100];
Byte[] byteObjectArray = ArrayUtils.toObject(byteArray);
Stream<Byte> byteObjectStream = Arrays.stream(byteObjectArray);
Morph21
  • 1,111
  • 6
  • 18