pe4enko
pe4enko

Reputation: 354

Parse string with java 8 streams

I have ip address string like "192.168.1.1". Is it possible to parse string using java 8 streams and get primitive byte array as a result. Currently i have code

Arrays.stream(address.split("\\."))
      .map(UnsignedBytes::parseUnsignedByte)
      .toArray(Byte[]::new);

where is UnsignedBytes is guava class which return byte, but this code return Byte[] not byte[]

Update: Yes, i read about why ByteStream class is absent. My question is about, is it possible to get byte array using java-8 streams, without overhead such as create intermediate list.

Upvotes: 3

Views: 4591

Answers (2)

mfulton26
mfulton26

Reputation: 31254

You can use Pattern.splitAsStream(CharSequence) use a ByteArrayOutputStream in a collector:

byte[] bytes = Pattern.compile("\\.")
        .splitAsStream(address)
        .mapToInt(Integer::parseInt)
        .collect(
                ByteArrayOutputStream::new,
                ByteArrayOutputStream::write,
                (baos1, baos2) -> baos1.write(baos2.toByteArray(), 0, baos2.size())
        )
        .toByteArray();

Collect code adapted from https://stackoverflow.com/a/32470838/3255152.

Upvotes: 1

Robert
Robert

Reputation: 8663

You could just use Java's InetAddress class.

 InetAddress i = InetAddress.getByName("192.168.1.1");
 byte[] bytes = i.getAddress();

Upvotes: 3

Related Questions