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

查看:20
本文介绍了根据键列表获取子 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为地图中不存在的键添加一个过滤器

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

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

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