加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 将所有键从LinkedHashMap提取到列表的方法

发布时间:2020-12-14 05:28:45 所属栏目:Java 来源:网络整理
导读:我正在使用许多LinkedHashMap,它们是LinkedHashMap Long,Long LinkedHashMap Long,Double或LinkedHashMap Long,Integer. 我的目标是找到或创建一个方法,该方法将返回List Long与上述LinkedHashMap Long,...中的所有键以相同的顺序.排序很重要,这就是为什么我
我正在使用许多LinkedHashMap,它们是LinkedHashMap< Long,Long> LinkedHashMap< Long,Double>或LinkedHashMap< Long,Integer>.

我的目标是找到或创建一个方法,该方法将返回List< Long>与上述LinkedHashMap< Long,...>中的所有键以相同的顺序.排序很重要,这就是为什么我不认为我可以使用Set< Long>的myMap.keySet().此外,我还有许多其他方法只接受List< Long>作为输入,所以我想要所需的方法返回该对象类型,所以我可以继续使用这些方法.

编写一个方法来返回,例如LinkedHashMap< Long,Long>足够简单:

private static List<Long> getLongKeys(LinkedHashMap<Long,Long> target) {
    List<Long> keys = new ArrayList<Long>();

    for(Map.Entry<Long,Long> t : target.entrySet()) {
        keys.add(t.getKey());
    }
    return keys;
}

然而,我需要编写几乎相同的方法,除了LinkedHashMap< Long,Double>和LinkedHashMap< Long,Integer>.

有什么办法可以概括我粘贴的方法来接受所有三种类型:LinkedHashMap< Long,Integer>?

解决方法

The ordering is important which is why I don’t think I can use myMap.keySet() which is a Set

LinkedHashMap的Map#keySet()方法将以插入顺序返回该集合.以下是Map文档的引用:

The order of a map is defined as the order in which the iterators on the map’s collection views return their elements. Some map implementations,like the TreeMap class,make specific guarantees as to their order; others,like the HashMap class,do not.

所以,您不需要为此写一个单独的方法.像keySet()和entrySet()这样的方法将只返回插入顺序中的条目.

那么,如果你真的想要一个List< Keys&gt,那么你可以直接做:

List<Long> keys = new ArrayList<>(target.keySet());

..无论你想要一个列表.你根本不需要这个方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读