Tiya
Tiya

Reputation: 563

How to loop through a byte array in Java 8?

I want to convert the following code to use Lambdas and Streams and/or any other Java 8 functionality.

I am new to Java 8 and tried converting the below code to Java 8 but couldn't find any function like 'forEach' that would fit my scenario.

    private String getMacAddress() {
    InetAddress ip;
    try {
        ip = InetAddress.getLocalHost();
        logger.log(LogLevel.LEVEL_INFO,"Current IP address : " + ip.getHostAddress());
        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
        byte[] mac = network.getHardwareAddress();
        logger.log(LogLevel.LEVEL_INFO,"Current MAC address : ");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
        }
        return sb.toString();
    } catch (UnknownHostException e) {
        logger.log(LogLevel.LEVEL_ERROR,e.getMessage());
    } catch (SocketException e){
        logger.log(LogLevel.LEVEL_ERROR,e.getMessage());
    }
}

Upvotes: 0

Views: 2001

Answers (2)

D&#225;niel Somogyi
D&#225;niel Somogyi

Reputation: 800

if you want to use a stream in java, you first have to invoke it. Collections have a .stream() function, for Arrays you can use the Arrays-library by Arrays.stream(mac).

This allows you to use the typical stream-functions like forEach, map or filter.

For your particular case, I'd go with a map (map bytes to formatted strings), and then concat them:

Arrays
 .stream(mac)
 .map(e -> String.format("%02X", e))
 .collect(Collectors.joining("-");

Note, that java Streams must be collected by a so-called collector, if you want to fetch the data.

Edit: also note, That Arrays.stream takes an argument of Type T[], so primitive typed arrays won't work...

Upvotes: 1

FredvN
FredvN

Reputation: 544

Convert you byte array to a stream of Integers. From that point on you can use stream functions to map them to the right format and join them.

 ByteArrayInputStream inputStream = new ByteArrayInputStream(mac);
 IntStream intStream = IntStream.generate(inputStream::read)
                                .limit(inputStream.available());
 String result = intStream .mapToObj(b -> { return String.format("%02X",(byte)b);} )
                           .collect(Collectors.joining("-"));

Upvotes: 1

Related Questions