Java 如何正确收集(collector.toMap)? publicmap foo()抛出SocketException{ var networkInterfaces=NetworkInterface.getNetworkInterfaces(); 返回Collections.list(networkInterfaces.stream()) .filter(iFace->**iFace.getName()**.startsWith(“w”)) .map(this::getEthernet) .collect(Collectors.toMap(**iFace.getName()???**,Function.identity()); } 公共以太网getEthernet(网络接口网络接口){ //返回以太网 }

Java 如何正确收集(collector.toMap)? publicmap foo()抛出SocketException{ var networkInterfaces=NetworkInterface.getNetworkInterfaces(); 返回Collections.list(networkInterfaces.stream()) .filter(iFace->**iFace.getName()**.startsWith(“w”)) .map(this::getEthernet) .collect(Collectors.toMap(**iFace.getName()???**,Function.identity()); } 公共以太网getEthernet(网络接口网络接口){ //返回以太网 },java,java-stream,Java,Java Stream,如何正确执行collect以获取iFace.getName()作为每个流元素的键和Ethernet对象作为值?您需要在collect中调用getEthernet,而不是在映射中,您的代码可以如下所示: public Map<String, Ethernet> foo() throws SocketException { var networkInterfaces = NetworkInterface.getNetworkInterfaces(); return Col

如何正确执行collect以获取
iFace.getName()
作为每个流元素的键和Ethernet对象作为值?

您需要在
collect
中调用
getEthernet
,而不是在映射中,您的代码可以如下所示:

public Map<String, Ethernet> foo() throws SocketException {
    var networkInterfaces = NetworkInterface.getNetworkInterfaces();
    return Collections.list(networkInterfaces).stream()
        .filter(iFace -> **iFace.getName()**.startsWith("w"))
        .map(this::getEthernet)
        .collect(Collectors.toMap(**iFace.getName()????**, Function.identity()));
}

public Ethernet getEthernet(NetworkInterface networkInterface) {
    //return Ethernet       
}

你的意思是类似于
网络接口::getName
?(在第二种情况下)
return Collections.list(networkInterfaces).stream()
        .filter(iFace -> iFace.getName().startsWith("w"))
        .collect(Collectors.toMap(NetworkInterface::getName, this::getEthernet));