简体   繁体   中英

Java Hashmap Iterating getting KeySet

So in my Java program I loop through my entire Hashmap when the program is about to close, getting both the key and value to store into a file.

I would like to know how to get the key, currently it loops through the Hashmap and only gets the value.

The code in question:

public HashMap<String, Integer> timers = new HashMap<String, Integer>();       
for(int times : timers.values()){
       int playerTime = times;
}

try this

    for (Entry<String, Integer> e : timers.entrySet()) {
        String key = e.getKey();
        Integer value = e.getValue();
    }

Use entry set to retrieve the entries and iterate over the entryset.

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#entrySet()

You could use entrySet method to get each and every entry holding key and value and can iterate over the set as below:

 Map<String, Integer> timers = new HashMap<String, Integer>();
 for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
}

Alternatively, if you want to iterate just over keys, you could use keySet method (just like you iterating over values) and iterate over the keys of a hashmap like:

 Map<String, Integer> timers = new HashMap<String, Integer>();
 for (String key : map.keySet()) {
    System.out.println(key);
    System.out.println(map.get(key));//will print value associated with key
}

I would suggest streaming the entrySet :

timers.entrySet().stream()
  .forEach(entry -> storeTimer(entry.getKey(), entry.getValue());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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