(Map)

版权声明:Java基础,个人笔记。 https://blog.csdn.net/liu19951104/article/details/81623589

1.Map集合

现实生活中,我们常会看到这样的一种集合:IP地址与主机名,身份证号与个人,系统用户名与系统用户对象等,这种一一对应的关系,就叫做映射。Java提供了专门的集合类用来存放这种对象关系的对象,即java.util.Map接口。

  • Collection中的集合,元素是孤立存在的(理解为单身),向集合中存储元素采用一个个元素的方式存储。

  • Map中的集合,元素是成对存在的(理解为夫妻)。每个元素由键与值两部分组成,通过键可以找对所对应的值。

  • Collection中的集合称为单列集合,Map中的集合称为双列集合。

  • 需要注意的是,Map中的集合不能包含重复的键,值可以重复;且每个键只能对应一个值。

1.1Map常用子类

通过查看Map接口描述,看到Map有多个子类。常用的子类为HashMap集合、LinkedHashMap集合。

  • HashMap<K,V>:存储数据采用的哈希表结构,元素的存取顺序不能保证一致。由于要保证键的唯一、不重复,需要重写键的hashCode()方法、equals()方法。

  • LinkedHashMap<K,V>:HashMap下有个子类LinkedHashMap,存储数据采用的哈希表结构+链表结构。通过链表结构可以保证元素的存取顺序一致;通过哈希表结构可以保证的键的唯一、不重复,需要重写键的hashCode()方法、equals()方法。

tips:Map接口中的集合都有两个泛型变量<K,V>,在使用时,要为两个泛型变量赋予数据类型。两个泛型变量<K,V>的数据类型可以相同,也可以不同。

1.2 Map接口中的常用方法

Map接口中定义了很多方法,常用的如下:

  • public V put (K key, V vaule):把指定的键与指定的值添加到Map集合中
  • public V remove(Object key):把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值
  • public V get(Object key): 根据指定的键,在Map集合中获取对应的值
  • public containKey(Object key):判断集合中是否包含指定的键
  • public Set<K> keySet():获取Map集合中所有的键,存储到Set集合中
  • public Set<Map.Entry<K,V>>  EntrySet():获取到Map集合中所有的键值对对象的集合(Set集合)
public class Test01 {
    public static void main(String[] args) {
        //创建 map对象
        Map<String,String> map = new HashMap<>();
        //添加元素到集合
        String s1 = map.put("马猪皮", "cool");
        System.out.println(s1);
        map.put("马猪皮","cool01");
        String s2 = map.put("马猪皮", "cool02");
        System.out.println(s2);
        System.out.println(map);
        String s = map.remove("李晨");
        System.out.println(s);
        System.out.println(map);
    }
}
/*null
cool01
{马猪皮=cool02}
null
{马猪皮=cool02}*/

使用put方法时,若指定的键(key)在集合中没有,则没有这个键对应的值,返回null,并把指定的键值添加到集合中;

若指定的键(key)在集合中存在,则返回值为集合中键对应的值(该值为替换前的值),并把指定键所对应的值,替换成指定的新值

1.3 Map集合遍历键找值方式

键找值方式:即通过元素中的键,获取键所对应的值

 public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("梁总","咸阳");
        map.put("鱼总","咸阳");
        map.put("梁总","日本");
        map.put("刘哥","西安");       
        Set<String> str = map.keySet();
        for (String s1 : str) {
            String s2 = map.get(s1);
            System.out.println(s1+"---->"+s2);  //梁总---->日本
        }                                       //刘哥---->西安
    }                                           //鱼总---->咸阳                                     
}

Map中存放的是两种对象,一种称为key(键),一种称为value(值),它们在在Map中是一一对应关系,这一对对象又称做Map中的一个Entry(项)。Entry将键值对的对应关系封装成了对象。即键值对对象,这样我们在遍历Map集合时,就可以从每一个键值对(Entry)对象中获取对应的键与对应的值。

既然Entry表示了一对键和值,那么也同样提供了获取对应键和对应值的方法:

  • public K getKey():获取Entry对象中的键。
  • public V getVaule():获取Entry对象中的值。

在Map集合中也提供了获取所有Entry对象的方法:

  • public Set<Map.Entry<K,V>>  EntrySet(): 获取到Map集合中所有的键值对对象的集合(Set集合)。

1.4Map集合遍历键值对方式

键值对方式:即通过集合中每个键值对(Entry)对象,获取键值对(Entry)对象中的键与值。

Entry键值对对象遍历Map集合的原理:

  • Map中存放的是两种对象,一种称为key(键),一种称为value(值),它们在在Map中是一一对应关系,这一对对象又称做Map 中的一个Entry(项)。Entry将键值对的对应关系封装成了对象。即键值对对象,这样我们在遍历Map集合时,就可以从每一个键值对(Entry)对象中获取对应的键与对应的值。

操作步骤与图解:

  1. 获取Map集合中,所有的键值对(Entry)对象,以Set集合形式返回。方法提示:EntrySet()()

  2. 遍历包含键值对(Entry)对象的Set集合,得到每一个键值对(Entry)对象。

  3. 通过键值对(Entry)对象,获取Entry对象中的键与值。 方法提示:getKey(),getVaule()

public class Test {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("梁总","咸阳");
        map.put("鱼总","咸阳");
        map.put("梁总","日本");
        map.put("刘哥","西安");              
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry.getKey()+"----->"+ entry.getValue());
        }
    }
}

1.5 HashMap存储自定义类型键值

演示代码如下图:

//定义学生类
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;
    }

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

    @Override // 重写equals方法与hashcode方法,确保唯一性
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, age);
    }
}
  • 当给HashMap中存放自定义对象时,如果自定义对象作为key存在,这时要保证对象唯一,必须复写对象的hashCode和equals方法

  • 如果要保证map中存放的key和取出的顺序一致,可以使用java.util.LinkedHashMap集合来存放

1.6 LinkedHashMap

LinkedHashMap,它是链表和哈希表组合的一个数据存储结构。 (可以保证集合的顺序)

演示代码如下:

public class LinkedHashMapDemo {
    public static void main(String[] args) {
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("邓超", "孙俪");
        map.put("李晨", "范冰冰");
        map.put("刘德华", "朱丽倩");
        Set<Entry<String, String>> entrySet = map.entrySet();
        for (Entry<String, String> entry : entrySet) {
            System.out.println(entry.getKey() + "  " + entry.getValue());
        }
    }     // 邓超 = 孙俪 李晨=范冰冰 刘德华=朱丽倩  //
}

2 JDK9对集合添加的优化

通常,我们在代码中创建一个集合(例如,List 或 Set ),并直接用一些元素填充它。 实例化集合,几个 add方法 调用,使得代码重复。而在Java 9中,添加了几种集合工厂方法,更方便创建少量元素的集合、map实例。新的List、Set、Map的静态工厂方法可以更方便地创建集合的不可变实例。

例子:

public class HelloJDK9 {  
    public static void main(String[] args) {  
        Set<String> str1=Set.of("a","b","c");  
        //str1.add("c");这里编译的时候不会错,但是执行的时候会报错,因为是不可变的集合  
        System.out.println(str1);  
        Map<String,Integer> str2=Map.of("a",1,"b",2);  
        System.out.println(str2);  
        List<String> str3=List.of("a","b");  
        System.out.println(str3);  
    }  
} 

需要注意以下两点:

1:of()方法只是Map,List,Set这三个接口的静态方法,其父类接口和子类实现并没有这类方法,比如 HashSet,ArrayList等等;

2:返回的集合是不可变的;

3 Debug追踪

                                        

4  案例介绍

按照斗地主的规则,完成洗牌发牌的动作。

public class Poker01 {
    public static void main(String[] args) {
        //创建一个集合存储扑克牌的索引和牌面
        Map<Integer, String> poker = new HashMap<>();
        //创建一个集合存储扑克牌的索引
        ArrayList<Integer> pokerIndex = new ArrayList<>();
        //创建一个list集合存储扑克牌的花色
        List<String> colors = List.of("♠", "♥", "♣", "♦");
        //创建一个list集合存储扑克牌的数字
        List<String> numbers = List.of("2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3");
        //定义索引并初始化
        int index = 0;
        //将特殊牌大小王添加进去
        poker.put(index, "大王");
        pokerIndex.add(index);
        index++;
        poker.put(index, "小王");
        pokerIndex.add(index);
        index++;
        //遍历花色和数字的集合,并将其存入poker集合中
        for (String number : numbers) {
            for (String color : colors) {
                poker.put(index, color + number);
                pokerIndex.add(index);
                index++;
            }
        }
        //利用Collections中的shuffle方法打乱索引,达到洗牌的目的
        Collections.shuffle(pokerIndex);
        //创建4个数组,分别储存三个玩家的牌和底牌
        ArrayList<Integer> play01 = new ArrayList<>();
        ArrayList<Integer> play02 = new ArrayList<>();
        ArrayList<Integer> play03 = new ArrayList<>();
        ArrayList<Integer> diPai = new ArrayList<>();
        //遍历pokerIndex索引,将索引按要求分给玩家和底牌
        for (int i = 0; i < pokerIndex.size(); i++) {
            Integer in = pokerIndex.get(i);
            if (i >= 51) {
                diPai.add(in);
            } else if (i % 3 == 0) {
                play01.add(in);
            } else if (i % 3 == 1) {
                play02.add(in);
            } else if (i % 3 == 2) {
                play03.add(in);
            }
        }
        //将玩家和数组的牌进行排序
        Collections.sort(play01);
        Collections.sort(play02);
        Collections.sort(play03);
        Collections.sort(diPai);
        lookPoker("梁总", poker, play01);
        lookPoker("鱼总", poker, play02);
        lookPoker("邵总", poker, play03);
        lookPoker("底牌", poker, diPai);

    }
        //创建方法,遍历存储索引的集合,得到每一个索引,,也就是k,调用map方法里的get(K k)获取牌面
    public static void lookPoker(String name, Map<Integer, String> poker, ArrayList<Integer> list) {
        System.out.print(name + ":");
        for (Integer in : list) {
            System.out.print(poker.get(in) + " ");
        }
        System.out.println();
    }
}

猜你喜欢

转载自blog.csdn.net/liu19951104/article/details/81623589
Map