javaSE(10)(Map集合)

测试HashMap:
package zz.itheima.map;

import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

public class TestHashMap {

    public static void main(String[] args) {
        //测试HashMap
        HashMap<String, String> hm = new HashMap<>();
        //存储
// V put(K key, V value) 键重复的话,值会覆盖
        hm.put("CN", "chinese");
        hm.put("JP", "japan");
        hm.put("US", "usa");
        System.out.println(hm);
        //删除
// void clear()
// V remove(Object key)根据键删除
        hm.remove("JP");
        System.out.println(hm);
        //判断
// boolean containsKey(Object key) 先判断hashCode 然后判断equals
        System.out.println(hm.containsKey("JP"));
// boolean containsValue(Object value) 判断equals
        System.out.println(hm.containsValue("usa"));
// boolean isEmpty()
        //获取
// Set<Map.Entry<K,V>> entrySet()
        Set hs = hm.entrySet();
        System.out.println(hs);//获取键值对
// V get(Object key)通过键获取值
        System.out.println(hm.get("CN"));
// Set<K> keySet()获取所有键的集合
        Set keys = hm.keySet();
        System.out.println(keys);
// int size()集合的容量
// Collection<V> values()集合中所有的值
        System.out.println(hm.size());
        Collection valuses = hm.values();
        System.out.println(valuses);
    }
}
运行结果:
{JP=japan, US=usa, CN=chinese}
{US=usa, CN=chinese}
false
true
[US=usa, CN=chinese]
chinese
[US, CN]
2
[usa, chinese]
测试LinkedHashMap:
package zz.itheima.map;

import java.util.LinkedHashMap;

public class TestLinkedHashMap {

    public static void main(String[] args) {
        // 测试LinkedHashMap 维护插入顺序为遍历顺序
        LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();
        lhm.put("a", 1);
        lhm.put("b", 2);
        lhm.put("c", 3);
        lhm.put("d", 4);
        lhm.put("e", 5);
        System.out.println(lhm);

    }

}
运行结果:
{a=1, b=2, c=3, d=4, e=5}
测试TreeMap:
package zz.itheima.map;

import java.util.TreeMap;

public class TestTreeMap {

    public static void main(String[] args) {
        //测试TreeMap
        TreeMap<String, Integer> tm = new TreeMap<>();
        //不允许null键,允许null值
        tm.put("a", 1);
        tm.put("b", 1);
        tm.put("d", 1);
        tm.put("c", 1);
        tm.put("e", 1);
        // tm.put(null, 1);不允许null键
        System.out.println(tm);//键的自然顺序排序
        //键是自定义对象时,会怎样?
    /* TreeMap<Student, Integer> stus = new TreeMap<>(); stus.put(new Student("b", 20), 1); stus.put(new Student("c", 21), 1);// java.lang.ClassCastException stus.put(new Student("a", 20), 1);//因为是按照自然顺序排序所以自定义的类型无法判断所谓的自然属性 System.out.println(stus);*/
        //独有方法
// public Map.Entry<K,V> ceilingEntry(K key)
        System.out.println(tm.ceilingEntry("a"));//大于等于a的键值对
// public K ceilingKey(K key)
        System.out.println(tm.ceilingKey("a"));//大于等于a的键
// public Map.Entry<K,V> firstEntry()
        System.out.println(tm.firstEntry());//第一个键值对
// public K firstKey()
        System.out.println(tm.firstKey());//第一个键
// public Map.Entry<K,V> lastEntry()
// public K lastKey()
// public Map.Entry<K,V> higherEntry(K key)
        System.out.println(tm.higherEntry("a"));//大于a的键值对
// public K higherKey(K key)
// public Map.Entry<K,V> lowerEntry(K key)
        System.out.println(tm.lowerEntry("b"));//小于b的键值对
// public K lowerKey(K key)

    }

}
运行结果:
{a=1, b=1, c=1, d=1, e=1}
a=1
a
a=1
a
b=1
a=1
测试containsKey:
package zz.itheima.map;

import java.util.HashMap;

public class TestContainsKey {

    public static void main(String[] args) {
        //测试containsKey(如果键为自定义类型时,怎么保证唯一性)
        HashMap<Student, Integer> hm=new HashMap<>();
        hm.put(new Student("aaa", 20), 1);
        hm.put(new Student("bbb", 21), 1);
        hm.put(new Student("aaa", 20), 1);
        System.out.println(hm);
    }

}
运行结果:
{Student [name=aaa, age=20]=1, Student [name=bbb, age=21]=1}
测试Map集合的迭代器:
package zz.itheima.map;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

public class TestIteratorMap {

    public static void main(String[] args) {
        //测试Map集合的迭代器
        HashMap<String, String> hm = new HashMap<>();
        hm.put("CN", "China");
        hm.put("JP", "Japan");
        hm.put("RU", "Russia");
        hm.put("USA", "American");
        System.out.println(hm);
// 思考:能用ForEach或昨天的迭代器直接对Map集合进行遍历吗?
// 如果只遍历所有的键,Set<K> keySet()把所有的键放在一个集合里面存放
        Set keys = hm.keySet();//集合中存放了所有键
        Iterator it = keys.iterator();//遍历键
        while (it.hasNext()) {
            System.out.println(it.next());
        }
// 如果只遍历所有的值,Collection<V> values()
        Collection values = hm.values();//集合中存放了所有值
        it = values.iterator();//遍历值
        while (it.hasNext()) {
            System.out.println(it.next());
        }
// 如果要成对遍历,则有如下两种方式:
// 方式一:获得所有的key,然后根据key找到value
        keys = hm.keySet();//得到所有 的键集合
        Iterator<String> itt = keys.iterator();//遍历键集合
        while (itt.hasNext()) {
            String key = itt.next();//得到单个的键
            String val = hm.get(key);//根据单个的键得到单个的值
            System.out.println(key+"="+val);
        }
// 方式二:Map.Entry接口,用于获取键值对的集合
        System.out.println("方式二:Map.Entry接口,用于获取键值对的集合");
        for (Entry<String, String> o : hm.entrySet()) {
            System.out.println(o);//得到键值对,就相当于直接输出hm一样
            System.out.println(o.getKey());//得到所有的key
            System.out.println(o.getValue());//得到所有的值
        }
        System.out.println("************************");
        Iterator<Entry<String, String>> iit = hm.entrySet().iterator();//直接遍历键值对
        while (iit.hasNext()) {
            Entry<String , String> o = iit.next();//遍历键值对,那么得到的就是键值对
            System.out.println(o);
            System.out.println(o.getKey());
            System.out.println(o.getValue());
        }
    }

}
运行结果:
{JP=Japan, USA=American, RU=Russia, CN=China}
JP
USA
RU
CN
Japan
American
Russia
China
JP=Japan
USA=American
RU=Russia
CN=China
方式二:Map.Entry接口,用于获取键值对的集合
JP=Japan
JP
Japan
USA=American
USA
American
RU=Russia
RU
Russia
CN=China
CN
China
************************
JP=Japan
JP
Japan
USA=American
USA
American
RU=Russia
RU
Russia
CN=China
CN
China
Map里面存List省市级联:
package zz.itheima.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

public class ShengShiJiLian {

    public static void main(String[] args) {
        //Map里面存List 省市级联
        List<String> hnCity=new ArrayList<String>();
        hnCity.add("郑州市");
        hnCity.add("洛阳市");

        List<String> sdCity=new ArrayList<String>();
        sdCity.add("济南市");
        sdCity.add("青岛市");

        HashMap<String,List<String>> prov=new HashMap<String, List<String>>();
        prov.put("hn", hnCity);
        prov.put("sd", sdCity);

        Scanner sc=new Scanner(System.in);
        System.out.println("请选择省份:1.河南 2.山东");
        int sel=sc.nextInt();

        if(sel==1)
        {
            System.out.println(prov.get("hn"));
        }
        if(sel==2)
        {
            System.out.println(prov.get("sd"));
        }
    }
}
运行结果:
请选择省份:1.河南  2.山东
1
[郑州市, 洛阳市]
例子1:
package zz.itheima.map;

import java.util.HashMap;
import java.util.Set;

public class Demo1 {

    public static void main(String[] args) {
        // 案例:使用HashMap存储图书信息,ISBN作为键,图书对象(书名、价格)作为值,
                // 分别实现添加、查找和删除、换行输出所有图书信息
        HashMap<String , Book> hm = new HashMap<>();
        //添加
        hm.put("1234", new Book("aaa", 10));
        hm.put("5678", new Book("bbb", 10));
        hm.put("67889", new Book("ccc", 10));
        System.out.println(hm);
        //查找
        if (hm.containsKey("1234")) {
            System.out.println("存在");
        }else {
            System.out.println("不存在");
        }
        //删除
        String keyName = "1234";
        hm.remove(keyName);
        System.out.println(hm);
        //输出所有图书信息
        Set<String > keys = hm.keySet();
        for (String  temp : keys) {
            System.out.println(temp +"="+hm.get(temp));
        }
    }

}
运行结果
{5678=Book [name=bbb, price=10], 1234=Book [name=aaa, price=10], 67889=Book [name=ccc, price=10]}
存在
{5678=Book [name=bbb, price=10], 67889=Book [name=ccc, price=10]}
5678=Book [name=bbb, price=10]
67889=Book [name=ccc, price=10]
例子2:
package zz.itheima.map;

import java.util.HashMap;
import java.util.Set;

public class Demo2 {

    public static void main(String[] args) {
        // 练习:使用HashMap存储学生信息,学号(整数)作为键,学生对象(姓名、年龄)作为值
        // 1.添加学生,测试键能否重复 2.根据一个学号查找该生是否存在,如果存在输出该生信息 
        // 3.输出学生总数 4.换行输出所有的学号
        HashMap<Integer, Student> hm=new HashMap<Integer, Student>();
        hm.put(1234, new Student("张三", 10));
        hm.put(5678, new Student("李四", 10));
        hm.put(6789, new Student("王五", 10));
        System.out.println(hm);

        int key=1234567;
        if(hm.containsKey(key))
            System.out.println(hm.get(key));
        else {
            System.out.println("不存在");
        }

        System.out.println("学生总数:"+hm.size());

        Set<Integer> keys=hm.keySet();
        for (Integer temp : keys) {
            System.out.println(temp);
        }
    }

}
运行结果:
{5678=Student [name=李四, age=10], 1234=Student [name=张三, age=10], 6789=Student [name=王五, age=10]}
不存在
学生总数:3
5678
1234
6789
例子3:
package zz.itheima.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Demo3 {

    public static void main(String[] args) {
        // 练习:模拟省市级联使用HashMap存储班级—学生信息
        List<Student> classOne=new ArrayList<Student>();
        classOne.add(new Student("aaa", 20));
        classOne.add(new Student("bbb", 20));
        classOne.add(new Student("ccc", 20));

        List<Student> classTwo=new ArrayList<Student>();
        classTwo.add(new Student("rty", 20));
        classTwo.add(new Student("fgh", 20));
        classTwo.add(new Student("asd", 20));

        HashMap<String, List<Student>> hm=new HashMap<String, List<Student>>();
        hm.put("一班", classOne);
        hm.put("二班", classTwo);

        System.out.println(hm.get("二班"));
    }

}
运行结果:
[Student [name=rty, age=20], Student [name=fgh, age=20], Student [name=asd, age=20]]
bean类:
package zz.itheima.map;

public class Book {
    private String name;
    private int price;

    public Book(String name, int price) {
        super();
        this.name = name;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + price;
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Book other = (Book) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (price != other.price)
            return false;
        return true;
    }
    @Override
    public String toString() {
        return "Book [name=" + name + ", price=" + price + "]";
    }

}
package zz.itheima.map;

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    @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;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
}

你可能感兴趣的:(Map集合)