V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
cencoroll
V2EX  ›  问与答

Java 相关,用 list 去匹配 map 的 key,返回 map 的 value 的用法?

  •  1
     
  •   cencoroll · 2023-01-16 14:45:04 +08:00 · 813 次点击
    这是一个创建于 457 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请问 java 中有没有 stream 的方法或者使用别的算法之类的去完成这个逻辑?

    我有: List<String> list; Map<String, Integer> keyMap;

    如果 list 的值命中 keyMap 里的 key 了,就返回一个 List<Integer> valueList 这样

    5 条回复    2023-01-17 09:24:39 +08:00
    Nooooobycat
        1
    Nooooobycat  
       2023-01-16 14:55:24 +08:00
    list.stream().map(keyMap::get).collect(Collectors.toList());

    这样可以吗
    superedlimited
        2
    superedlimited  
       2023-01-16 14:59:55 +08:00   ❤️ 1
    map.keyset().filter(el -> list.include(el)).map(el -> keyMap.get(el))
    Leviathann
        3
    Leviathann  
       2023-01-16 15:09:49 +08:00
    list
    filter get from map not null
    map
    issakchill
        4
    issakchill  
       2023-01-16 15:18:15 +08:00
    public <T> List<T> getByKeyList(Map<Integer, T> map, List<Integer> idList) {
    if (CollectionUtil.isEmpty(map) || CollectionUtil.isEmpty(idList)) {
    return new ArrayList<>();
    }

    return idList.stream()
    .map(map::get)
    .filter(Objects::nonNull)
    .collect(Collectors.toList());
    }
    cencoroll
        5
    cencoroll  
    OP
       2023-01-17 09:24:39 +08:00
    @Nooooobycat
    @superedlimited
    @Leviathann
    @issakchill
    感谢,昨天改 bug 改得头大,脑子转不过来了。谢谢大佬们!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   6002 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 02:15 · PVG 10:15 · LAX 19:15 · JFK 22:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.