基于键列表获取子HashMap的最佳方法是什么? [英] what is the best way to get a sub HashMap based on a list of Keys?

查看:54
本文介绍了基于键列表获取子HashMap的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HashMap,我想获得一个新的HashMap,它仅包含第一个HashMap中的元素,其中K属于特定列表.

I have a HashMap and I would like to get a new HashMap that contains only the elements from the first HashMap where K belongs to a specific List.

我可以浏览所有键并填写新的HashMap,但我想知道是否有更有效的方法?

I could look through all the keys and fillup a new HashMap but I was wondering if there is a more efficient way to do it?

谢谢

推荐答案

对于Java8流,有一个实用的(优雅的)解决方案.如果 keys 是要保留的密钥列表,而 map 是源 Map .

With Java8 streams, there is a functional (elegant) solution. If keys is the list of keys to keep and map is the source Map.

keys.stream()
    .filter(map::containsKey)
    .collect(Collectors.toMap(Function.identity(), map::get));

完整示例:

    List<Integer> keys = new ArrayList<>();
    keys.add(2);
    keys.add(3);
    keys.add(42); // this key is not in the map

    Map<Integer, String> map = new HashMap<>();
    map.put(1, "foo");
    map.put(2, "bar");
    map.put(3, "fizz");
    map.put(4, "buz");

    Map<Integer, String> res = keys.stream()
        .filter(map::containsKey)
        .collect(Collectors.toMap(Function.identity(), map::get));

    System.out.println(res.toString());

打印: {2 = bar,3 = fizz}

编辑为地图中缺少的键添加过滤器

EDIT add a filter for keys that are absent from the map

这篇关于基于键列表获取子HashMap的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆