Convert Set<String> to Set<InetAddress> in Java in a cleaner way

94 views Asked by At

I have the following code:

Set<String> ips = allowedIpsToDescriptions.keySet();

where allowedIpsToDescriptions is a Map<String, String>

I'm trying to convert Set<String> to Set<InetAddress> and here's my code:

Set<InetAddress> allowedIpsInetAddr = new HashSet<>();
    
    for (String ip : ips) {
      InetAddress inetAddress = InetAddress.getByName(ip);
      allowedIpsInetAddr.add(inetAddress);
    }

Is there a cleaner / more efficient way of doing this using streams perhaps?

2

There are 2 answers

0
Mohamedabotir On

I think this is good way to implement but you should handle null as expected input to prevent localhost as it is the default value returned by getHostName. Then ensure that input is pure url without port to prevent UnknownHostException.

3
John Kugelman On

Ideally you could use map to call InetAddress.getByName on each string:

// Doesn't compile.
Set<InetAddress> allowedIpsInetAddr = ips.stream()
    .map(InetAddress::getByName)
    .collect(Collectors.toSet());

Unfortunately this fails to compile:

error: incompatible thrown types UnknownHostException in functional expression
    .map(InetAddress::getByName)
         ^

map callbacks can't throw checked exceptions like UnknownHostException. You can work around this by converting them into UncheckedIOExceptions:

Set<InetAddress> allowedIpsInetAddr = ips.stream()
    .map(ip -> {
        try {
            return InetAddress.getByName(ip);
        }
        catch (UnknownHostException e) {
            throw new UncheckedIOException(e);
        }
    })
    .collect(Collectors.toSet());