英文:
Convert two while loop code to java 8 stream code
问题
以下是您要求的代码的翻译部分:
public static InetAddress getInetAddress() throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = networkInterfaces.nextElement();
Enumeration<InetAddress> nias = ni.getInetAddresses();
while (nias.hasMoreElements()) {
InetAddress ia = nias.nextElement();
if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
return ia;
}
}
}
return null;
}
英文:
I was using simple InetAddress.getLocalHost().getHostAddress() but for one of the server it was giving 127.0.0.0 ip address, which was not expected ip address.
To get actual ip address from server, i am using now below code but want to make it simpler.
Can we make below code simper with java 8 stream code?
public static InetAddress getInetAddress() throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
Enumeration<InetAddress> nias = ni.getInetAddresses();
while (nias.hasMoreElements()) {
InetAddress ia = (InetAddress) nias.nextElement();
if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
return ia;
}
}
}
return null;
}
答案1
得分: 0
以下是您要翻译的内容:
public static InetAddress getInetAddress() throws SocketException {
return Collections
.list(NetworkInterface.getNetworkInterfaces())
.stream()
.flatMap(ni -> Collections.list(ni.getInetAddresses()).stream())
.filter(ia -> !ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address)
.findFirst()
.orElse(null);
}
英文:
It is possible to use Collections.list to convert the enumeration to ArrayList
and then use List's stream
and related Stream API functions to filter out unnecessary instances of InetAddress
and select the first one matching the criteria:
public static InetAddress getInetAddress() throws SocketException {
return Collections
.list(NetworkInterface.getNetworkInterfaces())
.stream() // Stream<NetworkInterface>
.flatMap(ni -> Collections.list(ni.getInetAddresses()).stream()) // Stream<InetAddress>
.filter(ia -> !ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address)
.findFirst() // Optional<InetAddress>
.orElse(null);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论