In Java 8, is there a ByteStream class?
No, it does not exist. Actually, it was explicitly not implemented so as not to clutter the Stream API with tons of classes for every primitive type.
Quoting a mail from Brian Goetz in the OpenJDK mailing list:
Short answer: no.
It is not worth another 100K+ of JDK footprint each for these forms
which are used almost never. And if we added those, someone would
demand short, float, or boolean.Put another way, if people insisted we had all the primitive
specializations, we would have no primitive specializations. Which
would be worse than the status quo.
Create a Stream from a byte[] to a primitive byte Stream
A Stream<Byte>
is about as good as a ByteStream of primitives would be, since Byte#valueOf
returns cached instances of the boxed values (and the compiler handles boxing and unboxing for you). So then the only trick is to turn your byte[]
into a Stream<Byte>
.
One way to do that would be to create an IntStream
of indexes, and then map those indexes into lookups into your byte[]
:
byte[] byteArray = "hello".getBytes();
Stream<Byte> byteStream = IntStream.range(0, byteArray.length)
.mapToObj(i -> byteArray[i]);
I don't know of any helper method in the JDK that does this for you.
when i use Java 8 Stream.of primitive type, the result is confused
Stream.of
only accepts Objects as its arguments. A byte
isn't an Object, but a byte
array is. If a
is an array of byte
, then Stream.of(a)
can only mean "stream of this one object, which is an array".
If you have a Byte[]
array, then each element of the array is an object, so the compiler can guess that's what you mean.
There is information here about how you can stream a byte array:
In Java 8, is there a ByteStream class?
ArrayList of byte[] to byte[] using stream in Java
Try this.
List<byte[]> list = Arrays.asList("abc".getBytes(), "def".getBytes());
byte[] result = list.stream()
.collect(
() -> new ByteArrayOutputStream(),
(b, e) -> b.write(e, 0, e.length),
(a, b) -> {}).toByteArray();
System.out.println(new String(result));
// -> abcdef
java 8: how to stream an array of int, extract low bytes, and create an array of byte
Unfortunately, steams don't support the byte
type directly; i.e,. there is no ByteStream
specialization like there are for int
and long
1.
If you insist on using streams, a reasonably efficient solution is to use a ByteArrayOutputStream
to collect the bytes:
ByteArrayOutputStream baos(myintarray.length);
Arrays.stream(myintarray).forEachOrdered(i -> baos.write((byte)i));
byte[] byteArray = baos.toArray();
This only copies the array once. A for loop and explicit array insertion is going to be better still:
byte[] byteArray = new byte[myintarray.length];
for (int i = 0; i < myintarray.length; i++) {
byteArray[i] = (byte)myintarray[i];
}
Probably slightly more concise than the streams version, and about as fast as you'll get in Java.
If you really insist on a 1-liner with Stream
s, you can get a Byte[]
rather than a byte[]
like so:
Arrays.stream(myintarray).boxed().map(Integer::byteValue)
.collect(Collectors.toList()).toArray(new Byte[myintarray.length]);
This involves a crapload of boxing and you end up with a much larger and slower Byte[]
, but hey you used a pure Java 8 solution, right?
1 Combinatorial explosion arguments notwithstanding, this has always seemed like an unfortunate omission to me, given the key nature of byte[]
in many input/output oriented operations.
Convert InputStream to byte array in Java
You can use Apache Commons IO to handle this and similar tasks.
The IOUtils
type has a static method to read an InputStream
and return a byte[]
.
InputStream is;
byte[] bytes = IOUtils.toByteArray(is);
Internally this creates a ByteArrayOutputStream
and copies the bytes to the output, then calls toByteArray()
. It handles large files by copying the bytes in blocks of 4KiB.
Using lambda expression of Java 8, convert ListByte to primitive byte[], without external libraries
You can try doing like this:
listByte.stream().collect(ByteArrayOutputStream::new, (baos, i) -> baos.write((byte) i),
(baos1, baos2) -> baos1.write(baos2.toByteArray(), 0, baos2.size()))
.toByteArray()
Java 8 Streams : The method boxed() is undefined for the type StreamByte
The method boxed()
is designed only for streams of some primitive types (IntStream
, DoubleStream
, and LongStream
) to box each primitive value of the stream into the corresponding wrapper class (Integer
, Double
, and Long
respectively).
The expression Arrays.stream(toObjects(data))
returns a Stream<Byte>
which is already boxed since there is no such thing as a ByteStream
class.
Related Topics
How to Get Backspace \B to Work in Eclipse's Console
JPA Onetomany Not Deleting Child
Gson Custom Seralizer for One Variable (Of Many) in an Object Using Typeadapter
Exception in Thread "Main" Java.Util.Nosuchelementexception
Using Javamail to Connect to Gmail Smtp Server Ignores Specified Port and Tries to Use 25
What's in an Eclipse .Classpath/.Project File
How to Use Parameters, Request and Session Objects Present in Actioncontext
How to Write a Key Listener to Track All Keystrokes in Java
Please Explain About Insertable=False and Updatable=False in Reference to the JPA @Column Annotation
What Are the Differences Between "Generic" Types in C++ and Java
Is There a Method for String Conversion to Title Case
Mockito: Invaliduseofmatchersexception
Increasing Heap Space in Eclipse: (Java.Lang.Outofmemoryerror)
Does Java Support Let's Encrypt Certificates
How to Read Request Body Multiple Times in Spring 'Handlermethodargumentresolver'