Reputation: 354
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
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
Reputation: 8663
You could just use Java's InetAddress class.
InetAddress i = InetAddress.getByName("192.168.1.1");
byte[] bytes = i.getAddress();
Upvotes: 3