Get keys from HashMap in Java

后端 未结 14 2636
野的像风
野的像风 2020-12-04 07:03

I have a Hashmap in Java like this:

private Map team1 = new HashMap();

Then I fill it like th

相关标签:
14条回答
  • 2020-12-04 08:03

    To get Key and its value

    e.g

    private Map<String, Integer> team1 = new HashMap<String, Integer>();
      team1.put("United", 5);
      team1.put("Barcelona", 6);
        for (String key:team1.keySet()){
                         System.out.println("Key:" + key +" Value:" + team1.get(key)+" Count:"+Collections.frequency(team1, key));// Get Key and value and count
                    }
    

    Will print: Key: United Value:5 Key: Barcelona Value:6

    0 讨论(0)
  • 2020-12-04 08:04
    public class MyHashMapKeys {
    
        public static void main(String a[]){
            HashMap<String, String> hm = new HashMap<String, String>();
            //add key-value pair to hashmap
            hm.put("first", "FIRST INSERTED");
            hm.put("second", "SECOND INSERTED");
            hm.put("third","THIRD INSERTED");
            System.out.println(hm);
            Set<String> keys = hm.keySet();
            for(String key: keys){
                System.out.println(key);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题