簡體   English   中英

如何正確使用 collect (Collectors.toMap)?

[英]How can I use collect (Collectors.toMap) correctly?

考慮:

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
}

如何正確執行 collect 以獲取iFace.getName()作為鍵和以太網 object 作為每個 stream 元素的值?

您需要在collect中調用getEthernet而不是之前在 map 中調用。 您的代碼可能如下所示:

return Collections.list(networkInterfaces).stream()
        .filter(iFace -> iFace.getName().startsWith("w"))
        .collect(Collectors.toMap(NetworkInterface::getName, this::getEthernet));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM