【问题标题】:How can I use collect (Collectors.toMap) correctly?如何正确使用 collect (Collectors.toMap)?
【发布时间】:2021-07-23 22:01:32
【问题描述】:

考虑:

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() 作为键和以太网对象作为每个流元素的值?

【问题讨论】:

  • 你的意思是像NetworkInterface::getName这样的东西吗? (第二种情况)

标签: java java-stream


【解决方案1】:

您需要在collect 中调用getEthernet,而不是之前在地图中。您的代码可能如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2020-12-27
    • 1970-01-01
    • 2022-01-22
    • 2018-09-13
    • 2017-02-26
    • 1970-01-01
    相关资源
    最近更新 更多