For basic use, HashMap is the best, I described how to iterate over it, easier than using an iterator:
public static void main (String[] args) { //a map with key type : String, value type : String Map<String,String> mp = new HashMap<String,String>(); mp.put("John","Math"); mp.put("Jack","Math"); map.put("Jeff","History"); //3 differents ways to iterate over the map for (String key : mp.keySet()){ //iterate over keys System.out.println(key+" "+mp.get(key)); } for (String value : mp.values()){ //iterate over values System.out.println(value); } for (Entry<String,String> pair : mp.entrySet()){ //iterate over the pairs System.out.println(pair.getKey()+" "+pair.getValue()); } }
Quick explanation:
for (String name : mp.keySet()){
means: "For the whole line of map keys, we will do something, and at each iteration we will call the key" name "(this may be what you want, this is a variable)
Like this:
public String[] getAllKeys(){ int i = 0; String allkeys[] = new String[buckets.length]; KeyValue val = buckets[i]; //Look at the first one if(val != null) { allkeys[i] = val.key; i++; } //Iterate until there is no next while(val.next != null){ allkeys[i] = val.next.key; val = val.next; i++; } return allkeys; }
source share