問題描述
我正在使用許多 LinkedHashMap
,它們是 LinkedHashMap<Long, Long>
、LinkedHashMap<Long, Double>
或 LinkedHashMap
.
I am working with many LinkedHashMap
that are either LinkedHashMap<Long, Long>
, LinkedHashMap<Long, Double>
or LinkedHashMap<Long, Integer>
.
我的目標是找到或創建一個方法,該方法將返回一個 List<Long>
,其中包含上述 LinkedHashMap<Long,...>
中的所有鍵順序相同.排序很重要,這就是為什么我認為我不能使用 myMap.keySet()
,它是一個 Set<Long>
.此外,我還有許多其他方法只接受 List<Long>
作為輸入,因此我希望所需的方法以該對象類型返回,以便我可以繼續使用這些方法.
My objective is to find or create a method that will return a List<Long>
with all the keys in the above LinkedHashMap<Long,...>
in the same order. The ordering is important which is why I don't think I can use myMap.keySet()
which is a Set<Long>
. Also, I have many other methods that accept only List<Long>
as the input so I would like the desired method to return in that object type so I can continue to use these methods.
為 LinkedHashMap<Long, Long>
編寫返回此值的方法非常簡單:
Writing a method to return this for, e.g., a LinkedHashMap<Long, Long>
is easy enough:
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
和 LinkedHashMap
之外,我需要編寫幾乎相同的方法.
However, then I need to write almost identical methods except for LinkedHashMap<Long, Double>
and LinkedHashMap<Long, Integer>
.
有什么方法可以概括我粘貼的方法以接受所有三種類型:LinkedHashMap<Long, Long>
, LinkedHashMap<Long, Double>
或 LinkedHashMap
?
Is there any way I can generalize the method that I pasted to accept all three types: LinkedHashMap<Long, Long>
, LinkedHashMap<Long, Double>
or LinkedHashMap<Long, Integer>
?
推薦答案
順序很重要,這就是為什么我認為我不能使用 myMap.keySet() 一個 Set
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 Map#keySet()
method for LinkedHashMap
will return the set in insertion order. Here's a quote from Map
documentation:
地圖的順序定義為地圖集合視圖上的迭代器返回其元素的順序.一些地圖實現,如 TreeMap 類,對它們的順序做出特定的保證;其他的,比如 HashMap 類,則不需要.
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()
等方法將僅返回插入順序中的條目.
So, you don't need to write a separate method for that. Methods like keySet()
and entrySet()
will return the entries in the insertion order only.
好吧,如果你真的想要一個List<Keys>
,那么你可以直接這樣做:
Well, if you really want a List<Keys>
, then you can directly do:
List<Long> keys = new ArrayList<>(target.keySet());
.. 任何你想要一個列表的地方.你根本不需要這個方法.
.. wherever you want a List. You don't need the method at all.
這篇關于將 LinkedHashMap 中的所有鍵提取到列表中的方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!