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.
2 Answers 2
You could just use Java's InetAddress class.
InetAddress i = InetAddress.getByName("192.168.1.1");
byte[] bytes = i.getAddress();
3 Comments
getAddress()[0]
. I think you need to reverse the byte array to suit OP's need.bytes[0]
, 168 in bytes[1]
, and so on. Which makes sense to me.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.
Bytes.toArray
to get a primitive array.collect
in this answer: stackoverflow.com/a/36613808/3487617