How to iterate a map in java?

I need to iterate through BucketMap and get all the keys , but how can I get something like buckets[i].next.next.next.key , for example, without doing it manually, as I tried here:

 public String[] getAllKeys() { int j = 0; //index of string array "allkeys" String allkeys[] = new String[8]; for(int i = 0; i < buckets.length; i++) { //iterates through the bucketmap if(buckets[i] != null) { //checks wether bucket has a key and value allkeys[j] = buckets[i].key; //adds key to allkeys j++; // counts up the allkeys index after adding key if(buckets[i].next != null) { //checks wether next has a key and value allkeys[j] = buckets[i].next.key; //adds key to allkeys j++; } } } return allkeys; } 

Also, how can I initialize String[] allkeys using the version of j we get after iterating as an index?

+17
source share
3 answers

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()){ //Do Something } 

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; } 
+44
source

See if it helps,

  HashMap< String, String> map = new HashMap<>(); Set<String> keySet = map.keySet(); Iterator<String> iterator = keySet.iterator(); while(iterator.hasNext()) { //iterate over keys } //or iterate over entryset Iterator<Entry<String, String>> iterator2 = map.entrySet().iterator(); while(iterator2.hasNext()) { Entry<String, String> next = iterator2.next(); //get key next.getKey(); //get value next.getValue(); } 
+3
source

With Java 8, I would suggest you use the Stream API.

This will allow you to iterate over the map in a much more convenient way:

 public void iterateUsingStreamAPI(Map<String, Integer> map) { map.entrySet().stream() // ... .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())); } 

Check out more examples on map iteration in Java .

0
source

Source: https://habr.com/ru/post/1265903/


All Articles