jayteezer
jayteezer

Reputation: 115

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

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?

Upvotes: 0

Views: 129

Answers (2)

Mohamedabotir
Mohamedabotir

Reputation: 1

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.

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 362037

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

Upvotes: 0

Related Questions