简体   繁体   English

转换集<String>设置<InetAddress>以更简洁的方式使用 Java

[英]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>其中allowedIpsToDescriptionsMap<String, String>

I'm trying to convert Set<String> to Set<InetAddress> and here's my code:我正在尝试将Set<String>转换为Set<InetAddress> ,这是我的代码:

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 .我认为这是实现的好方法,但您应该按预期输入处理null以防止 localhost 因为它是getHostName返回的默认值。 Then ensure that input is pure url without port to prevent UnknownHostException .然后确保输入是没有端口的纯 url 以防止UnknownHostException

Ideally you could use map to call InetAddress.getByName on each string:理想情况下,您可以使用map在每个字符串上调用InetAddress.getByName

// 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 . map回调不能抛出UnknownHostException等已检查异常。 You can work around this by converting them into UncheckedIOException s :您可以通过将它们转换为UncheckedIOException来解决此问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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