adam bien's blog

Converting a byte[] to Stream 📎

The following snippet converts a byte[] array to a Stream using ByteBuffer:

import java.nio.ByteBuffer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.jupiter.api.Test;

public class ByteArrayTest {
    
    @Test
    public void byteArrayToStream(){
        byte bytes[] = new byte[]{0xC,0xA,0xF,0xE,0xB,0xA,0xB,0xE};
        var buffer = ByteBuffer.wrap(bytes);
        var message = Stream.generate(() -> buffer.get()).
                        limit(buffer.capacity()).
                        map(b -> Integer.toHexString(b)).
                        collect(Collectors.joining());
        System.out.println(message);
    }    

Output: cafebabe