简体   繁体   中英

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?

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 .

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 UncheckedIOException s :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM