java集合------Map集合

来源:互联网 发布:上海淘宝摄影基地 编辑:程序博客网 时间:2024/06/10 18:48

Map集合的特点?
1、可以存储键值对的元素。
2、将键映射到值的对象。
3、一个映射不能包含重复的键,每个键最多只能映射到一个值。
4、Map是一个接口。


Map集合和Collection集合的区别?
1、Map集合存储元素是成对出现的,Map集合的键是唯一的,值是可重复的
1、Collection集合存储元素是单独出现的,Collection的子体系Set是唯一的,List是可重复的。
2、Map集合的数据结构只针对键有效,跟值无关。
2、Collection集合的数据结构是针对元素有效。


HashMap LinkedHashMap TreeMap 基于哈希表的Map接口 Map 接口的哈希表和链接列表 红黑树的Map接口 保证键的唯一性 保证键的唯一性,具有可预知的迭代顺序(添加的顺序和输出的顺序完全一致) 保证键的排序和唯一性

添加功能
V put(K key, V value) :添加元素。
如果键是第一次存储,就直接存储元素,返回null。如果键不是第一次存储,就用值把以前的值替换掉,返回以前的值。

删除功能
void clear():移除所有的键值对元素。
V remove(Object key) :根据键删除键值对元素,返回删除的值。

判断功能
boolean containsKey(Object key) :判断集合是否包含指定的键
boolean containsValue(Object value):判断集合是否包含指定的值
boolean isEmpty():判断集合是否为空

获取功能
V get(Object key):根据键获取值
Set keySet():获取集合中所有键的集合
Collection values():获取集合中所有值得集合

长度功能
int size() :返回集合中键值对的对数


V put(K key, V value) 方法。返回值为V类型
map是如何做到当键的唯一性的呢?一个键只对应一个值。
通过put方法,当添加的元素的键相同的时候,值会覆盖已经存在的那个值。

public class MapDemo {    public static void main(String[] args) {        //创建集合对象        Map<String, String> map = new HashMap<String, String>();        //添加元素        //如果键是第一次存储,就直接存储元素,返回null        //如果键不是第一次存储,就用值把以前的值替换掉,返回以前的值。(键已经存在,值就覆盖)        System.out.println(map.put("梨梨", "21"));        //null        System.out.println(map.put("梨梨", "22"));        //21        //输出集合元素        System.out.println(map);                        //{梨梨=22}    }}

基本方法的使用介绍:
remove方法:

public class MapDemo {    public static void main(String[] args) {        //创建集合对象        Map<String, String> map = new HashMap<String, String>();        //添加元素        map.put("梨梨", "21");        map.put("熊熊", "22");        map.put("菜菜", "12");        map.put("哈哈", "2");        //删除元素。传入键,返回对应的值,若键不存在,返回null        System.out.println("remove:" + map.remove("梨梨"));               //remove:21        System.out.println("remove:" + map.remove("lili"));             //remove:null        System.out.println("containsKey:" + map.containsKey("菜菜"));     //containsKey:true        System.out.println("size:" + map.size());                       //3        System.out.println("isEmpty:" + map.isEmpty());                 //isEmpty:falses        //输出集合元素        System.out.println(map);                                        //{哈哈=2, 熊熊=22, 菜菜=12}    }}

get方法

public class MapDemo {    public static void main(String[] args) {        //创建集合对象        Map<String, String> map = new HashMap<String, String>();        //创建元素并添加元素        map.put("梨梨", "21");        map.put("熊熊", "22");        map.put("菜菜", "12");        map.put("哈哈", "2");        //根据键获取值        System.out.println("get:" + map.get("菜菜"));     //get:12        //获得所有键的集合        Set<String> keySet = map.keySet();        //遍历所有键        for(String key : keySet){            System.out.println(key);        }        System.out.println("-------");        //获取所有值的集合        Collection<String> values = map.values();        for(String value:values){            System.out.println(value);        }    }}

输出:

get:12-------哈哈梨梨熊熊菜菜-------2212212

Map集合的遍历

有四种方法,可以去看我这篇文章:http://blog.csdn.net/qq_36748278/article/details/77921523


HashMap类

HashMap:是基于哈希表的Map接口实现,哈希表的作用是用来保证键的唯一性。

键和值都是String

public class MapDemo4 {    public static void main(String[] args) {        //创建集合对象        HashMap<String, String> hm = new HashMap<String, String>();        //创建元素并添加元素        hm.put("梨梨", "美丽");        hm.put("熊熊", "帅气");        hm.put("菜菜", "乖巧");        hm.put("哈哈", "搞笑");        hm.put("梨梨", "大方");     //会覆盖上面的"美丽"        Set<String> keySet = hm.keySet();        for(String key : keySet){            String value = hm.get(key);            System.out.println(key + "=" + value);;        }    }}

输出:

哈哈=搞笑梨梨=大方熊熊=帅气菜菜=乖巧

键是Integer值是String

public class MapDemo4 {    public static void main(String[] args) {        //创建集合对象        HashMap<Integer, String> hm = new HashMap<Integer, String>();        //创建元素并添加元素        hm.put(001 , "美丽");        hm.put(002 , "帅气");        hm.put(003 , "乖巧");        hm.put(004 , "搞笑");        hm.put(007 , "大方");     //会覆盖上面的"美丽"        //遍历        Set<Integer> keySet = hm.keySet();        for(Integer key : keySet){            String value = hm.get(key);            System.out.println(key + "=" + value);;        }        //集合的元素的字符串表示,不是遍历        System.out.println(hm);    }}

输出:

1=美丽2=帅气3=乖巧4=搞笑7=大方{1=美丽, 2=帅气, 3=乖巧, 4=搞笑, 7=大方}

键是String值是Student

public class MapDemo4 {    public static void main(String[] args) {        //创建集合对象        HashMap<Integer, Student> hm = new HashMap<Integer, Student>();        //创建元素        Student stu1 = new Student("梨梨", 21);        Student stu2 = new Student("菜菜", 3);        Student stu3 = new Student("熊熊", 22);        Student stu4 = new Student("哈哈", 1);        //添加元素        hm.put(001, stu1);        hm.put(002, stu2);        hm.put(004, stu3);        hm.put(005, stu4);        //遍历        Set<Integer> keySet = hm.keySet();        for(Integer key:keySet){            Student stu = hm.get(key);            System.out.println(key + "=" + stu.getName() + "," + stu.getAge());        }    }}

输出:

1=梨梨,212=菜菜,34=熊熊,225=哈哈,1

键是Student值是String
Student类如下:

public class Student {    private String name;    private int age;    public Student() {    }    public Student(String name, int age) {        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}
public class HashMapDemp2 {    public static void main(String[] args) {        //创建集合对象        HashMap<Student, String> hm = new HashMap<Student, String>();        //创建元素        Student stu1 = new Student("梨梨", 21);        Student stu2 = new Student("菜菜", 3);        Student stu3 = new Student("熊熊", 22);        Student stu4 = new Student("哈哈", 1);        Student stu5 = new Student("梨梨", 21);        hm.put(stu1, "001");        hm.put(stu2, "002");        hm.put(stu3, "003");        hm.put(stu4, "004");        hm.put(stu5, "005");        Set<Student> keySet = hm.keySet();        for(Student key:keySet){            String value = hm.get(key);            System.out.println(key.getName() + "," + key.getAge() + "," + value);        }    }}

输出:

梨梨,21,001熊熊,22,003梨梨,21,005菜菜,3,002哈哈,1,004

如果两个Student对象的成员变量值都相同,则为同一个对象。可以看成是同一个键,键相同,则值覆盖。而上面的代码却达不到这个效果。
为了达到这个效果,可以采用以下方法:
在Student类中加入这些代码即可达到效果。

@Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + age;        result = prime * result + ((name == null) ? 0 : name.hashCode());        return result;    }    @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Student other = (Student) obj;        if (age != other.age)            return false;        if (name == null) {            if (other.name != null)                return false;        } else if (!name.equals(other.name))            return false;        return true;    }

输出:

熊熊,22,003梨梨,21,005哈哈,1,004菜菜,3,002

LinkedHashMap

Map 接口的哈希表和链接列表实现,具有可预知的迭代顺序。

public class LinkedHashMapDemo {    public static void main(String[] args) {        //创建集合对象        LinkedHashMap<String, String> hm = new LinkedHashMap<String, String>();        //创建并添加元素        hm.put("123", "you");        hm.put("234", "are");        hm.put("345", "very");        hm.put("234", "good");        hm.put("345", "!");        //遍历        Set<String> keySet = hm.keySet();        for(String key:keySet){            String value = hm.get(key);            System.out.println(key + "=" + value);        }    }}

输出:

123=you234=good345=!

可以发现输出是有序的,什么顺序输入进去,就按照什么顺序输出来。
并且,当键相同时,值也被覆盖了。


TreeMap

是基于红黑树的Map接口的实现,可以保证键的排序和唯一性。

public class TreeMapDemo {    public static void main(String[] args) {        //创建集合对象        TreeMap<String, String> tm = new TreeMap<String, String>();        //创建元素并添加元素        tm.put("hello", "你好");        tm.put("very", ",");        tm.put("you", "你");        tm.put("very", "非常");        tm.put("nice", "棒");        //遍历集合        Set<String> keySet = tm.keySet();        for(String key:keySet){            String value = tm.get(key);            System.out.println(key + "," + value);        }    }}

输出:

hello,你好nice,棒very,非常you,你

可以发现,当键相同时,值进行了覆盖。
并且,还对键进行了排列。


键是Student对象,值是String
传入参数,指明排序的方法。

public class TreeMaoDemo2 {    public static void main(String[] args) {        //创建集合对象        //输出排序的方法        TreeMap<Student1, String> tm = new TreeMap<Student1, String>(new Comparator<Student1>() {            @Override            public int compare(Student1 s1, Student1 s2) {                int num = s1.getAge() - s2.getAge();                int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;                return num2;            }        });        //创建学生对象        Student1 stu1 = new Student1("梨梨", 21);        Student1 stu2 = new Student1("菜菜", 3);        Student1 stu3 = new Student1("熊熊", 22);        Student1 stu4 = new Student1("哈哈", 1);        Student1 stu5 = new Student1("菜菜", 18);        tm.put(stu1, "l");        tm.put(stu2, "la");        tm.put(stu3, "lal");        tm.put(stu4, "lala");        tm.put(stu5, "lalal");        //遍历集合        Set<Student1> keySet = tm.keySet();        for(Student1 key:keySet){            String value = tm.get(key);            System.out.println(key.getAge() + "," + key.getName() + "," + value );        }    }}

输出:

1,哈哈,lala3,菜菜,la18,菜菜,lalal21,梨梨,l22,熊熊,lal

HashMap集合中嵌套HashMap。
很简单。也就是第一层循环获得键对应的值,这个值又是一个集合,再循环的到这个集合对应的键和值既可以了。

/* * 衣服 *      001   男装 *              上衣      20   *              裤子      12 *      001   女装 *              裙子      30 *              裤子      20 */public class HashMapDemo3 {    public static void main(String[] args) {        //创建集合对象        HashMap<String, HashMap<String, Integer>> clothes = new HashMap<String, HashMap<String,Integer>>();        //创建男装对象        HashMap<String,Integer> manClothes = new HashMap<String, Integer>();        manClothes.put("上衣", 20);        manClothes.put("裤子", 12);        //把男装添加到大集合        clothes.put("001", manClothes);        //创建女装对象        HashMap<String,Integer> womanClothes = new HashMap<String, Integer>();        womanClothes.put("裙子", 30);        womanClothes.put("裤子", 20);        //把女装添加到大集合        clothes.put("002", womanClothes);        //遍历集合        Set<String> clothesKeySet = clothes.keySet();        for(String cloth:clothesKeySet){            System.out.println(cloth);            //键对应的值又是一个集合。同样的方式遍历就可以了            HashMap<String, Integer> clothesMap = clothes.get(cloth);            Set<String> clothesValueSet = clothesMap.keySet();            for(String clothesValueKey:clothesValueSet){                Integer clothesValueValue = clothesMap.get(clothesValueKey);                System.out.println("\t"+clothesValueKey+"---"+clothesValueValue);            }        }    }}

输出:

001    上衣---20    裤子---12002    裤子---20    裙子---30

HashMap集合的元素是ArrayList

/* *  * 男歌手 *      周杰伦 *      陈奕迅 * 女演员 *      赵丽颖 *      孙俪 * 女歌手 *      张碧晨 *      张靓颖 *  * */public class HashMapDemo4 {    public static void main(String[] args) {        //创建集合对象        HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();        //创建元素集合1        ArrayList<String> array1 = new ArrayList<String>();        array1.add("周杰伦");        array1.add("陈奕迅");        //创建元素集合1        ArrayList<String> array2 = new ArrayList<String>();        array2.add("赵丽颖");        array2.add("孙俪");        //创建元素集合1        ArrayList<String> array3 = new ArrayList<String>();        array3.add("张碧晨");        array3.add("张靓颖");        //把键值对添加到HashMap中        hm.put("男歌手", array1);        hm.put("女演员", array2);        hm.put("女歌手", array3);        Set<String> keySet = hm.keySet();        for(String key:keySet){            System.out.println(key);            //键对应的值是一个ArrayList集合,所以用ArrayList接收            ArrayList<String> value = hm.get(key);            for(String s:value){                System.out.println("\t" + s);;            }        }    }}

输出:

女歌手    张碧晨    张靓颖男歌手    周杰伦    陈奕迅女演员    赵丽颖    孙俪

ArrayList集合的元素是HashMap

public class ArrayListDemo {    public static void main(String[] args) {        //创建集合对象        ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String,String>>();        //创建元素1        HashMap<String, String> hm1 = new HashMap<String, String>();        hm1.put("梨梨", "可爱");        hm1.put("菜菜", "任性");        //创建元素1        HashMap<String, String> hm2 = new HashMap<String, String>();        hm2.put("熊大", "暖男");        hm2.put("熊二", "傻萌");        //创建元素1        HashMap<String, String> hm3 = new HashMap<String, String>();        hm3.put("熊芭比", "帅气");        hm3.put("熊北鼻", "可爱");        //把元素添加到ArrayList中        arrayList.add(hm1);        arrayList.add(hm2);        arrayList.add(hm3);        //遍历(arrayList中的类型都是HashMap<>类型)        for(HashMap<String, String> hm : arrayList){            //根据值(HashMap)获取对应的键和值            Set<String> keySet = hm.keySet();            for(String key : keySet){                String value = hm.get(key);                System.out.println(key + "," + value);            }        }    }}

输出:

梨梨,可爱菜菜,任性熊二,傻萌熊大,暖男熊北鼻,可爱熊芭比,帅气

原创粉丝点击