Java中HashMap的常用操作

1.定义哈希并给其赋值

HashMap hashMap = new HashMap<>();		
	hashMap.put(5, 2);
	hashMap.put(9, 2);
	hashMap.put(8, 1);
	hashMap.put(7, 3);
	hashMap.put(16, 1);
	hashMap.put(10, 2);
	hashMap.put(6, 2);
	//其实下面两个键值对是没有存的
	hashMap.put(5, 2);
	hashMap.put(5, 3);

当在hashmap中put的key在之前已经存过,则不会重复存储,会覆盖之前key对应的value

1.containsKey(Object key)方法,返回值为boolean,用于判断当前hashmap中是否包含key对应的key-value

2.containsValue(Object value)方法,返回值为boolean,用于判断当前hashmap中是否包含value对应的key-value

3.遍历hashmap的两种方式:

(1)利用haspmap.entrySet().iterator():利用迭代器,从Entry中取出键、取出值,推荐使用这种方式进行遍历,效率较高

Iterator> iterator = hashMap.entrySet().iterator();
	while (iterator.hasNext()) {
		Entry entry = iterator.next();
		Integer key = entry.getKey();
		Integer value = entry.getValue();
		System.out.print(key + "--->" + value);
		System.out.println();
	}

(2)利用hashmap.keySet().iterator():利用键的迭代器,每次取出一个键,再根据键,从hashmap中取出值,这种方式的效率不高,不推荐使用

Iterator iterator2 = hashMap.keySet().iterator();
		while (iterator2.hasNext()) {
			Integer key = iterator2.next();
			Integer value = hashMap.get(key);
			System.out.print(key + "---" + value);
			System.out.println();
		}

案例:有效括号

class Solution {
 private HashMap mappings;

	public Solution(){
    this.mappings = new HashMap();
    this.mappings.put(')', '(');
    this.mappings.put('}', '{');
    this.mappings.put(']', '[');
	}
	public boolean isValid(String s) {

    Stack stack = new Stack<>();

    for (int i = 0; i < s.length(); i++){
        char ch = s.charAt(i);
        if(ch == '(' || ch == '[' || ch == '{'){
            stack.push(ch);
        }else{
            if(stack.isEmpty()){
                return false;
            }

            char topChar = stack.pop();
            if(ch == ')' && topChar != '('){
                return false;
            }else if(ch == ']' && topChar != '['){
                return false;
            }else if(ch == '}' && topChar != '{'){
                return false;
            }
        }
    }

    return stack.isEmpty();
}

}

你可能感兴趣的:(Java,算法)