Java HashMap方法及实例 – keySet(), values(), containsKey()

Java HashMap方法及实例 – keySet(), values(), containsKey()

在这篇文章中,将讨论更多的方法。

keySet(): java.util.HashMap.keySet()它返回该Map中包含的键的Set视图。这个集合是由Map支持的,所以Map的变化会反映在集合中,反之亦然。
语法:

public Set keySet()
Java

返回:该Map中包含的键的集合视图

values(): java.util.HashMap.values() 它返回该Map中包含的值的集合视图。这个集合是由Map支持的,所以Map的变化会反映在集合中,反之亦然。

语法:

public Collection values()
Java

返回:该Map中包含的值的集合视图

containsKey(): java.util.HashMap.containsKey() 如果这个Map将一个或多个键映射到指定的值,它将返回true。
语法:

public boolean containsValue(Object value)
Java

参数:
value – 要测试其在该Map中的存在。
返回: 如果这个Map将一个或多个键映射到指定的值,则为true

实现:

// Java program illustrating usage of HashMap class methods
// keySet(), values(), containsKey()
import java.util.*;
public class NewClass
{
    public static void main(String args[])
    {
        // 1   Creation of HashMap
        HashMap<String, String> Geeks = new HashMap<>();
  
        // 2   Adding values to HashMap as ("keys", "values")
        Geeks.put("Language", "Java");
        Geeks.put("Platform", "Geeks For geeks");
        Geeks.put("Code", "HashMap");
        Geeks.put("Learn", "More");
  
        // 3  containsKey() method is to check the presence
        //    of a particluar key
        // Since 'Code' key present here, the condition is true
        if (Geeks.containsKey("Code"))
            System.out.println("Testing .containsKey : " +
                                           Geeks.get("Code"));
  
        // 4 keySet() method returns all the keys in HashMap
        Set<String> Geekskeys = Geeks.keySet();
        System.out.println("Initial keys  : " + Geekskeys);
  
  
        // 5  values() method return all the values in HashMap
        Collection<String> Geeksvalues = Geeks.values();
        System.out.println("Initial values : " + Geeksvalues);
  
        // Adding new set of key-value
        Geeks.put("Search", "JavaArticle");
  
        // Again using .keySet() and .values() methods
        System.out.println("New Keys : " + Geekskeys);
        System.out.println("New Values: " + Geeksvalues);
    }
}
Java

输出:

Testing .containsKey : HashMap
Initial keys  : [Language, Platform, Learn, Code]
Initial values : [Java, Geeks For geeks, More, HashMap]
New Keys : [Language, Platform, Search, Learn, Code]
New Values: [Java, Geeks For geeks, JavaArticle, More, HashMap]
Java

.entrySet() : java.util.HashMap.entrySet() 方法返回HashMap中存在的键和值的完整集合。
语法:

public Set<Map.Entry> entrySet()
Java

返回:
完整的键和值的集合

.getOrDefault : java.util.HashMap.getOrDefault()方法如果没有使用我们在HashMap中作为参数传递的键找到的值,则返回一个默认值。如果键的值已经存在于HashMap中,它将不会对其做任何事情。
这是一个非常好的方法,可以为尚未映射的键赋值,而不影响已经存在的键和值的集合。

语法:

default V getOrDefault(Object key,V defaultValue)
Java

参数:
key – 我们需要返回其映射值的键
defaultValue – HashMap中存在的键的默认值。
返回:
将未映射的键与默认值进行映射。

.replace() : java.util.HashMap.replace(key, value) or java.util.HashMap.replace(key, oldvalue, newvalue) 方法是一个java.util.HashMap类方法。
第1个方法接受key和value的集合,它将用参数中传递的新值替换已经存在的key的值。如果没有这样的集合,replace()方法将不做任何事情。
同时,如果在HashMap中找到key和old_Value,第2个方法将只替换已经存在的key-old_value的集合。

语法:

replace(k key, v value)
          or
replace(k key, v oldvalue, newvalue)
Java

参数:
key – 集合中的键与旧值。
value – 我们希望与指定的键一起成为新的值
oldvalue – 集合中的旧值,有指定的键
newvalue – 我们希望与指定的键一起成为新的值。
返回:
True – 如果值被替换
Null – 如果不存在这样的集合

.putIfAbsent java.util.HashMap.putIfAbsent(key, value) 方法被用来向HashMap插入一个新的键值集,如果相应的键值集存在。如果HashMap中已经存在这样的键值集,则返回空值。

语法:

public V putIfAbsent(key, value)
Java

参数:
key – 与指定值相关联的键。
value – 与指定的键相关联的值。

// Java Program illustrating HashMap class methods(). 
// entrySet(), getOrDefault(), replace(), putIfAbsent
import java.util.*;
public class NewClass
{
    public static void main(String args[])
    {
        // Creation of HashMap
        HashMap<String, String> Geeks = new HashMap<>();
  
        // Adding values to HashMap as ("keys", "values")
        Geeks.put("Language", "Java");
        Geeks.put("Code", "HashMap");
        Geeks.put("Learn", "More");
  
        // .entrySet() returns all the keys with their values present in Hashmap
        Set<Map.Entry<String, String>> mappingGeeks = Geeks.entrySet();
        System.out.println("Set of Keys and Values using entrySet() : "+mappingGeeks);
        System.out.println();
  
        // Using .getOrDefault to access value
        // Here it is Showing Default value as key - "Code" was already present
        System.out.println("Using .getorDefault : " 
                                    + Geeks.getOrDefault("Code","javaArticle"));
  
        // Here it is Showing set value as key - "Search" was not present
        System.out.println("Using .getorDefault : "
                                    + Geeks.getOrDefault("Search","javaArticle"));
        System.out.println();
  
        // .replace() method replacing value of key "Learn"
        Geeks.replace("Learn", "Methods");
        System.out.println("working of .replace()     : "+mappingGeeks);
        System.out.println();
  
        /* .putIfAbsent() method is placing a new key-value
            as they were not present initially*/
        Geeks.putIfAbsent("cool", "HashMap methods");
        System.out.println("working of .putIfAbsent() : "+mappingGeeks);
  
        /* .putIfAbsent() method is not doing anything
            as key-value were already present */
        Geeks.putIfAbsent("Code", "With_JAVA");
        System.out.println("working of .putIfAbsent() : "+mappingGeeks);
  
    }
}
Java

输出

Set of Keys and Values using entrySet() : [Language=Java, Learn=More, Code=HashMap]

Using .getorDefault : HashMap
Using .getorDefault : javaArticle

working of .replace()     : [Language=Java, Learn=Methods, Code=HashMap]

working of .putIfAbsent() : [Language=Java, cool=HashMap methods, Learn=Methods, Code=HashMap]
working of .putIfAbsent() : [Language=Java, cool=HashMap methods, Learn=Methods, Code=HashMap]
Java

remove(Object key): 如果存在的话,从这个Map上删除这个键的映射。

// Java Program illustrating remove() method using Iterator.
  
import java.util.*;
public class NewClass
{
    public static void main(String args[])
    {
        //  Creation of HashMap
        HashMap<String, String> Geeks = new HashMap<>();
  
        //  Adding values to HashMap as ("keys", "values")
        Geeks.put("Language", "Java");
        Geeks.put("Platform", "Geeks For geeks");
        Geeks.put("Code", "HashMap");
  
  
        //  .entrySet() returns all the keys with their values present in Hashmap
        Set<Map.Entry<String, String>> mappingGeeks = Geeks.entrySet();
        System.out.println("Set of Keys and Values : "+mappingGeeks);
        System.out.println();
  
        //  Creating an iterator
        System.out.println("Use of Iterator to remove the sets.");
        Iterator<Map.Entry<String, String>> geeks_iterator = Geeks.entrySet().iterator();
        while(geeks_iterator.hasNext())
        {
            Map.Entry<String, String> entry = geeks_iterator.next();
            //  Removing a set one by one using iterator
            geeks_iterator.remove(); // right way to remove entries from Map,
            // avoids ConcurrentModificationException
            System.out.println("Set of Keys and Values : "+mappingGeeks);
  
        }
    }
}
Java

输出

Set of Keys and Values : [Language=Java, Platform=Geeks For geeks, Code=HashMap]

Use of Iterator to remove the sets.
Set of Keys and Values : [Platform=Geeks For geeks, Code=HashMap]
Set of Keys and Values : [Code=HashMap]
Set of Keys and Values : []
Java

优势:

如果我们使用for循环,它在内部会被翻译成Iterator,但如果不明确使用Iterator,我们就不能在Iteration期间删除任何条目。这样做时,Iterator可能会抛出ConcurrentModificationException。因此,我们使用显式的Iterator和while循环来遍历。

参考资料:

https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册