① map集合中存放的都是一组组映射关系 (key=value)键值队; ② 在集合中允许嵌套,map集合Key不能重复 ;
put:1、添加集合元素的同时,它可以编辑原有的元素;如果说集合中没有Key对应的value,那么就往集合中添加元素;如果说集合中对应的Key有value值,则代表替换原有的值。 2、返回替换前Key对应的value值 3、提高的安全性,可以尽量减少数据的泄露; 4、Map集合映射关系May.Entry描述的伪代码;
应用一: 1、将学生作为键,地址作为值进行存储,名字年龄相同则被认定为一个人,最后输出; 2、最后按年龄进行排序; 3、需求改变、按姓名进行排序; 判重复思路: a、建立一个student类、实列化作为Key添加到map集合中 b、对学生进行判重
public class TreeMapDemo { public static void main(String[] args) { // Map<Student,String> map = new HashMap<>(); Map<Student,String> map = new TreeMap<>(new StuComp()); map.put(new Student("liuting",18), "beijing"); map.put(new Student("wangwang",22), "taibei"); map.put(new Student("xuyang",33), "dongjing"); map.put(new Student("shiyi",34), "taiwan"); map.put(new Student("liuting",18), "beijing"); map.put(new Student("liutingting",18), "beijing"); System.out.println(map.size()); Set<Entry<Student, String>> entrySet = map.entrySet(); for (Entry<Student, String> entry : entrySet) { System.out.println(entry.getKey() + "====" + entry.getValue()); } } } class Student implements Comparable<Student>{ private String name; private int 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 Student(String name, int age) { super(); this.name = name; this.age = age; } public Student() { super(); } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } @Override public int hashCode() { return this.getName().hashCode() + this.getAge()*39; } @Override public boolean equals(Object obj) { Student stu = (Student)obj; return this.getAge() ==stu.getAge() && this.getName().equals(stu.getName()); } @Override public int compareTo(Student o) { int num = this.getAge() - o.getAge(); if(num == 0) { return this.getName().compareTo(o.getName()); } return num; } } class StuComp implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { int num = o1.getName().compareTo(o2.getName()); if(num == 0) { return o1.getAge() - o2.getAge(); } return num; } }应用二: 统计字符串中字符出现次数 思路 1、将字符串转为字符数组,将这个字符串中的字符当作map集合中的key,将出现的次数作为value值; 2、当字符第一次出现的现象,那么用它在集合中进行寻找,返回值必然为null,之后该字符对应的值改为1 ; 3、如果说该字符不是第一次出现,该字符对应值不为null,然后应该+1 。
