Common methods of Java Map interface

Interface definitions:

The other parameters K and V are generic representations. Represents the types of key s and values that store numeric values in Map s, respectively.

 

1. View the number of elements

int size();

2. Judging whether Map is empty

boolean isEmpty();

3. Determine whether a Map includes a specified Key

boolean containsKey(Object key);

4. Determine whether a Map includes a specified Value

boolean containsValue(Object value);

5. Get the corresponding Value according to Key

V get(Object key);

6. Store a set of key-value pairs in Map

V put(K key, V value);

7. Move out a set of key-value pairs according to Key

V remove(Object key);

8. Copy data from another Map to the current Map

void putAll(Map<? extends K, ? extends V> m);

9. Clear Map

void clear();

Code example:

import java.util.*;
public class PutAndGet {

	public static void main(String[] args) {
		Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
		Map<Integer, Integer> map2 = new HashMap<Integer, Integer>();
		map1.put(1, 100);
		map1.put(2, 200);
		map1.put(3, 300);
		map2.put(11, 1100);
		map2.put(12, 1200);
		map2.put(13, 1300);
		// View the number of elements contained
		System.out.println(map1.size());
		System.out.println(map1);
		// Store data with a new key of 1, covering the original (1,100)
		map1.put(1,99);
		System.out.println(map1);
		// Get Value from Key
		System.out.println("map1 get key 2 is: "+map1.get(2));
		// Determine whether a Key or Value is included
		System.out.println("map1 There are key Element for 4? "+map1.containsKey(4));
		System.out.println("map1 There are Value Element 300? "+map1.containsValue(300));
		// Copy the elements in map 2 to map 1
		map1.putAll(map2);
		System.out.println("after copy, map1 now is: "+map1);
		System.out.println("after copy, map2 now is: "+map2);
		// Remove a set of key-value pairs from map 2 (via key)
		map2.remove(12);
		System.out.println("After remove 12, map2 is: "+map2);
		// Empty map2
		map2.clear();
		System.out.println("After clear, map2 is: "+map2+" and size is: "+map2.size());
	}
}

Output:

3

{1=100, 2=200, 3=300}

{1=99, 2=200, 3=300}

map1 get key 2 is: 200

map1 There are key Element 4? false

map1 There are Value Element 300? true

after copy, map1 now is: {1=99, 2=200, 3=300, 11=1100, 12=1200, 13=1300}

after copy, map2 now is: {11=1100, 12=1200, 13=1300}

After remove 12, map2 is: {11=1100, 13=1300}

After clear, map2 is: {} and size is: 0

Tags: Java

Posted on Fri, 11 Oct 2019 09:22:31 -0700 by Chris 96 WS6