0

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
jayteezer
  • 115
  • 2
  • 13

2 Answers2

0

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.

RBT
  • 24,161
  • 21
  • 159
  • 240
0

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());
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • How is this "cleaner / more efficient" than the original code? – Olivier Jun 03 '22 at 19:27
  • 1
    It isn't necessarily better. People who like functional idioms might prefer a streaming version. Then again, they might find the exception handling too ugly to bear. – John Kugelman Jun 03 '22 at 19:55
  • 1
    Someone who strongly prefers streaming could hide the exception handling inside a helper function so it's not such an eyesore. – John Kugelman Jun 03 '22 at 19:57