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

Time:06-04

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?

CodePudding user response:

i think this is good way to implement but you should handle null as expected input to prevent localhost as it is default returned by getHostName , and ensure that input is pure url without port to prevent UnknownHostException thanks.

CodePudding user response:

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());
  • Related