Java Map 及相应的一些操作总结

Map是我们在开发的时候经常会用到的,大致有以下几个操作,其中putAll方法是针对集合而言的操作,故不再进行说明,下面请看一下常用的知识点吧,尤其是keySet和Values两个方法及相应值的获取方式:

import java.util.Collection;

import java.util.HashMap;

import java.util.Map;

import java.util.Set;

public class Practice {

public static void main(String []args){
    Map map=new HashMap();
    map.put(1, "A");
    map.put(2, "B");
    map.put(3, "C");
    map.put(4, "D");
    map.put(5, "E");
    map.put(6, "F");
    map.put(7, "G");
    map.put(8, "H");
    map.put(9, "I");
    map.put(10, "J");
    System.out.println("-------------------分割线--------------------");
    Set keys=map.keySet();
    for(Object keysName: keys){
        System.out.println("KeyName: "+keysName);
    }
    System.out.println("-------------------分割线--------------------");
    Collection values=(Collection) map.values();
    for(Object valuesName: values){
        System.out.println("KeyName: "+valuesName);
    }

    System.out.println("-------------------分割线--------------------");
    System.out.println("map.hashCode()="+map.hashCode());
    System.out.println("-------------------分割线--------------------");
    System.out.println("map is empty?"+map.isEmpty());
    System.out.println("-------------------分割线--------------------");
    System.out.println("map has the key of 7?"+map.containsKey(7));
    System.out.println("-------------------分割线--------------------");
    System.out.println("map has the value of B?"+map.containsValue("B"));
    System.out.println("-------------------分割线--------------------");
    System.out.println("map has the value of O?"+map.containsValue("O"));
    map.clear();
    System.out.println("-------------------分割线--------------------");
    System.out.println("map is empty?"+map.isEmpty());
}

}

下面是程序运行的结果,对照一下,是不是感觉很方便呢?

——————-分割线——————–

KeyName: 1

KeyName: 2

KeyName: 3

KeyName: 4

KeyName: 5

KeyName: 6

KeyName: 7

KeyName: 8

KeyName: 9

KeyName: 10

——————-分割线——————–

KeyName: A

KeyName: B

KeyName: C

KeyName: D

KeyName: E

KeyName: F

KeyName: G

KeyName: H

KeyName: I

KeyName: J

——————-分割线——————–

map.hashCode()=640

——————-分割线——————–

map is empty?false

——————-分割线——————–

map has the key of 7?true

——————-分割线——————–

map has the value of B?true

——————-分割线——————–

map has the value of O?false

——————-分割线——————–

map is empty?true

,大概就是这样了。

上一篇:Electorn(桌面应用)自动化测试之Java+selenium实战例子


下一篇:SpringBoot报错:Failed to load ApplicationContext( Failed to bind properties under 'logging.level')