简体   繁体   中英

convert Object[] from stream to byte[]

I try to filter a byte[] , I want to remove line breaks from the stream

byte[] data = "y\neahbabydoit\nsothisistheway\ntodoit".getBytes();
Object[] tmp = IntStream.range(0, data.length).mapToObj(idx -> Integer.valueOf(data[idx]).byteValue()).filter(i -> i != 10).toArray();
System.out.println("src:"+Arrays.toString(data));
System.out.println("dst:"+Arrays.toString(tmp));

//works not!!
byte[] dest = (Byte[]) tmp; //help me here

The result (as expected) works (so far) but I'm not able to convert the result ( Object[] ) in an easy way back (to byte[] )...

src:[121, 10, 101, 97, 104, 98, ...
dst:[121, 101, 97, 104, 98, 97, ...

I know there are ways to solve this problem (see How to convert int[] to byte[] ) but I want to do it in an easy (stream-like) way...

any news from java 8 or later?

To save yourself the hassle of handling multi-byte characters, it may be a lot easier to just handle the stream of characters:

String result =
    data.chars()
        .filter(c -> c != '\n')
        .mapToObj(c -> String.valueOf((char) c))
        .collect(Collectors.joining());

As @Mureinik suggested, it is better to deal with characters rather than bytes, to answer your question, you can certainly use something like

Byte[] tmp = IntStream.range(0, data.length)
        .mapToObj(idx -> Integer.valueOf(data[idx]).byteValue())
        .filter(i -> i != 10)
        .toArray(Byte[]::new);

Collecting to a byte array is not straight with Java 8.
But by using ByteArrayOutputStream::new as supplier in the collect operation you can.
It is a little more verbose because of the checked exception handling in the body lambda because of the combiner but it also has some advantages : it doesn't perform any boxing byte to Byte and it doesn't create unnecessary variables.

byte[] data = "y\neahbabydoit\nsothisistheway\ntodoit".getBytes();
byte[] dest = IntStream.range(0, data.length)
                       .map(i -> data[i])
                       .filter(i -> i != 10)
                       .collect(ByteArrayOutputStream::new, ByteArrayOutputStream::write, (bos1, bos2) -> {
                           try {
                               bos2.writeTo(bos1);
                           } catch (IOException e) {
                              throw new RuntimeException(e);
                           }
                       })
                       .toByteArray();

System.out.println("src:" + Arrays.toString(data));
System.out.println("dst:" + Arrays.toString(dest));

Output :

src:[121, 10, 101, 97, 104, 98, 97, 98, 121, ...]

dst:[121, 101, 97, 104, 98, 97, 98, 121,...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM