V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
KamL
V2EX  ›  问与答

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

  •  1
     
  •   KamL · Jan 16, 2023 · 1515 views
    This topic created in 1209 days ago, the information mentioned may be changed or developed.

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

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

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

    5 replies    2023-01-17 09:24:39 +08:00
    Nooooobycat
        1
    Nooooobycat  
       Jan 16, 2023
    list.stream().map(keyMap::get).collect(Collectors.toList());

    这样可以吗
    superedlimited
        2
    superedlimited  
       Jan 16, 2023   ❤️ 1
    map.keyset().filter(el -> list.include(el)).map(el -> keyMap.get(el))
    Leviathann
        3
    Leviathann  
       Jan 16, 2023
    list
    filter get from map not null
    map
    issakchill
        4
    issakchill  
       Jan 16, 2023
    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());
    }
    KamL
        5
    KamL  
    OP
       Jan 17, 2023
    @Nooooobycat
    @superedlimited
    @Leviathann
    @issakchill
    感谢,昨天改 bug 改得头大,脑子转不过来了。谢谢大佬们!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3088 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 11:05 · PVG 19:05 · LAX 04:05 · JFK 07:05
    ♥ Do have faith in what you're doing.