简体   繁体   English

在哈希图中获取所有元素的最佳方法是什么?

[英]What is the best way to get all elements in a hashmap?

I know I can use .values() and .keyset() to get the respective keys/values on their own (from a hashmap). 我知道我可以使用.values().keyset()获取各自的键/值(从哈希图中)。 I am trying to get them together and return that in a get method. 我试图将它们放在一起,并以get方法返回它。

Could I use entryset() to get an entry, but do it in a loop to produce an array list of entryset's and then return that? 我可以使用entryset()获取一个条目,但是否在循环中生成一个条目集的数组列表,然后返回该列表? Not sure if that is the best way though. 不确定这是否是最好的方法。 Any advice? 有什么建议吗?

The entrySet() method already returns a collection of all of the entries (key/value pairs) in the map, not just a single entry. entrySet()方法已经返回了映射中所有条目(键/值对)的集合,而不仅仅是单个条目。 I think you want to just call this once and use the set that it returns instead of calling it in a loop and populating a list. 我认为您只想调用一次并使用它返回的集合,而不是循环调用并填充列表。

entrySet() returns a Set of all entries of HashMap. entrySet()返回HashMap所有条目的Set。

import java.util.HashMap;

import java.util.Set;

public class HashMapEntrySet {

public static void main(String[] arr) {

/* Create object of HashMap */

HashMap<Integer, String> obHashMap = new HashMap<Integer, String>();

/* Strore value in HashMap */

obHashMap.put(new Integer(1), "AAA");

obHashMap.put(new Integer(2), "BBB");

obHashMap.put(new Integer(3), "CCC");

obHashMap.put(new Integer(4), "DDD");

obHashMap.put(new Integer(5), "EEE");

/* Create a set of keys of hashmap */

Set obEntrySet = obHashMap.entrySet();

System.out.println("Set of entries : " + obEntrySet); } }

Use entrySet() on the Map to get a set of ALL entries in the Map . 使用entrySet()上的Map ,以获得一组中的所有条目的Map You can either return the whole set or iterate over it if additional manipulations need to be made. 您可以返回整个集合,也可以在整个集合上进行迭代(如果需要进行其他操作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM