Map system collection

Map system collection

Map(interface)

Features of map interface:

  1. Used to store arbitrary key-value pairs (key-value), store a pair of data

  2. key: disorder, no subscript, not repeatable (unique)

  3. value (value): disorder, no subscript, can be repeated

method:

put() saves the object into the collection, and associates the key value, and if the key is repeated, the original value is overwritten.

get (Object key) Get the corresponding value according to the key

set(k) returns all keys

Collection values() returns a Collection collection containing all values

Set (Map.Entry<K,V>) Set set with matching key value

Set<Map.Entry<K,V>> entrySet() returns the set view containing the mapping relationship in this map

SetkeySet() returns a set view of the keys contained in this map

//创建map集合
Map<String,String> map = new HashMap<>();
//添加元素
map.put("cn","中国");
map.put("uk","英国");
map.put("usa","美国");
//删除元素,通过key
map.remove("cn") ;
//遍历1.使用keySet()
//得到所有的key的set集合
Set<String> keyset = map.keySet();
//用增强for或者迭代器遍历存放key的set集合
for (String key:keyset
     ) {
    
    
    //使用map中的get(key)方法获取key对应的value值
    System.out.println(key+"--"+map.get(key));
}
//遍历2.使用entrySet方法
    Set<Map.Entry<String,String >> entries=map.entrySet();
for (Map.Entry<String,String > kv:entries
     ) {
    
    
    System.out.println(kv.getKey()+"--"+kv.getValue());
}

Traverse:

In keySet(), the key is stored in the set collection.

In entrySet(), the key and value are encapsulated into an entry (key-value pair), and then stored in the set collection. Map.Entry type key-value pair. Entry<K,V> is an internal interface. Use getkey() and getValue() to get the key and value respectively

//判断
System.out.println(map.containsKey("cn"));
System.out.println(map.containsValue("美国"));

HashMap(class)

SortedMap(interface)

TreeMap(class)

Guess you like

Origin blog.csdn.net/weixin_43903813/article/details/112298877