1.Map集合概述
- Interface Map
K:键的类型; V:值的类型 - 将键映射到值的对象;不能包含重复的键;每个键可以映射到最多一个值
举例:学生的学号和姓名
创建Map集合的对象
- 多态的方式
- 具体的实现类HashMap
package com.study_01;import java.util.HashMap;import java.util.Map;public class MapDemo01 {public static void main(String[] args) {// 创建集合对象Map<String,String> map = new HashMap<>();//V put (K key, V value) 将指定的值与该映射中的指定键相关联map.put("xiaoZ001","林青霞");map.put("xiaoZ002","张曼玉");map.put("xiaoZ003","王祖贤");map.put("xiaoZ003","柳岩");// 输出集合对象System.out.println(map);}}
2.Map集合的基本功能

package com.study_01;import java.util.HashMap;import java.util.Map;public class MapDemo02 {public static void main(String[] args) {// 创建集合对象Map<String,String> map = new HashMap<>();//V put (K key, V value) 将指定的值与该映射中的指定键相关联map.put("张无忌","赵敏");map.put("郭靖","黄蓉");map.put("杨过","小龙女");// 根据键删除键值对元素// System.out.println(map.remove("郭靖"));// System.out.println(map.remove("郭襄"));// 移除所有键值对元素// map.clear();// 判断集合是否包含指定的键// System.out.println(map.containsKey("郭靖"));// System.out.println(map.containsKey("郭襄"));// 判断集合是否为空// System.out.println(map.isEmpty());// 集合长度System.out.println(map.size());// 输出集合System.out.println(map);}}
3.Map集合的获取功能

package com.study_01;import java.util.Collection;import java.util.HashMap;import java.util.Map;import java.util.Set;public class MapDemo03 {public static void main(String[] args) {// 创建集合对象Map<String, String> map = new HashMap<>();// 添加元素map.put("张无忌", "赵敏");map.put("郭靖", "黄蓉");map.put("杨过", "小龙女");// 根据键获取值// System.out.println(map.get("张无忌"));// System.out.println(map.get("张三丰"));// Set<K> keySet() : 获取所有键的值// Set<String> keySet = map.keySet();// for (String i : keySet){// System.out.println(i);// }// 获取所有值的集合Collection<String> values = map.values();for (String i : values) {System.out.println(i);}}}
4.Map集合的遍历(方式1)
我们刚才存储的元素都是成对出现的,所以我们把Map看成是一个夫妻对的集合
遍历思路
- 把所有的丈夫给集中起来
- 遍历丈夫的集合,获取到每一个丈夫
- 根据丈夫去找对应的妻子
转换为Map集合中的操作:
- 获取所有键的集合。 用keySet0方法实现
- 遍历键的集合,获取到每一个键。用增强for实现
- 根据键去找值。用get(Object key)方法实现
package com.study_02;import java.util.HashMap;import java.util.Map;import java.util.Set;public class MapDemo01 {public static void main(String[] args) {// 创建集合对象Map<String,String> map = new HashMap<>();// t添加元素map.put("张无忌","赵敏");map.put("郭靖","黄蓉");map.put("杨过","小龙女");// 获取所有键的集合,用keySet()实现Set<String> keySet = map.keySet();// 遍历键的耳机和,获取到每一个键,用增强for实现for (String key : keySet) {String value = map.get(key);System.out.println(key+","+value);}}}
5.Map集合的遍历(方式2)
我们刚才存储的元素都是成对出现的,所以我们把Map看成是一个妻对的集合
遍历思路
- 获取所有结婚证的集合
- 遍历结婚证的集合,得到每一个结婚证
- 根据结婚证获取丈夫和妻子
转换为Map集合中的操作:
- 获取所有键值对对象的集合
- Set
> entrySet(:获取所有键值对对象的集合
- Set
- 遍历键值对对象的集合,得到每一个键值对对象
- 用增强for实现,得到每一个Map.Entry
- 根据键值对对象获取键和值
- 用getKey()得到键
- 用getValue()得到值 ```java package com.study_02;
import java.util.HashMap; import java.util.Map; import java.util.Set;
public class MapDemo02 {
public static void main(String[] args) {
// 创建集合对象
Map
// t添加元素map.put("张无忌","赵敏");map.put("郭靖","黄蓉");map.put("杨过","小龙女");// 获取所有键值对对象的集合Set<Map.Entry<String,String>> entrySet = map.entrySet();// 遍历键值对对象的集合,得到每一个键值对对象for (Map.Entry<String,String> me : entrySet) {String key = me.getKey();String value = me.getValue();System.out.println(key+"," + value);}// 根据键值对对象获取键和值}
}
<a name="7c04953f"></a>## 6.案例案例: HashMap集合存储学生对象并遍历需求:创建一个HashMap集合, 键是学号(String), 值是学生对象(Student)。存储三E个键值对元素,并遍历```javapackage com.study_03;import java.util.Objects;public class Student {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}public Student() {}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;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}}
package com.study_03;import java.util.HashMap;import java.util.Map;import java.util.Set;public class HashMapDemo {public static void main(String[] args) {// 创建HashMap集合对象HashMap<String,Student> hm = new HashMap<>();// 创建学生对象Student s1 = new Student("林青霞",30);Student s2 = new Student("张曼玉",35);Student s3 = new Student("王祖贤",33);// 把学生添加到集合hm.put("stu001",s1);hm.put("stu002",s2);hm.put("stu003",s3);// 键找值Set<String> set = hm.keySet();for (String key : set) {Student value = hm.get(key);System.out.println(key+","+value);}System.out.println("---------");Set<Map.Entry<String, Student>> entrySet = hm.entrySet();for (Map.Entry<String, Student> me : entrySet) {String key = me.getKey();Student value = me.getValue();System.out.println();}}}
7.案例
需求:创建一个HashMap集合,键是学生对象(Student), 值是居住地(String)。存储多个键值对元素,并遍历。
要求保证键的唯一性: 如果学生对象的成员变量值相同,我们就认为是同一个对象
package com.study_04;import java.util.Objects;public class Student {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}public Student() {}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;}@Overridepublic 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);}@Overridepublic int hashCode() {return Objects.hash(name, age);}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}}
package com.study_04;import java.util.HashMap;import java.util.Set;public class HashMapDemo {public static void main(String[] args) {// 创建HashMap集合对象HashMap<Student,String > hm = new HashMap<>();// 创建学生对象Student s1 = new Student("林青霞",30);Student s2 = new Student("张曼玉",35);Student s3 = new Student("王祖贤",33);Student s4 = new Student("王祖贤",33);// 把学生添加到集合hm.put(s1,"西安");hm.put(s2,"武汉");hm.put(s3,"郑州");hm.put(s4,"北京");// 遍历集合Set<Student> set = hm.keySet();for (Student key : set) {String value = hm.get(key);System.out.println(key+","+value);}}}
8.集合嵌套值ArrayList嵌套HashMap
需求:创建一个ArrayList集合, 存储三个元素,每一个元素都是HashMap, 每一个HashMap的键和值都是String, 并遍历
package com.study_05;import java.util.ArrayList;import java.util.HashMap;import java.util.Set;public class ArrayListCludeHashMapDemo {public static void main(String[] args) {// 创建ArrayLis集合ArrayList<HashMap<String, String>> array = new ArrayList<>();// 创建HashMap集合HashMap<String, String> hm1 = new HashMap<>();hm1.put("孙策", "大桥");hm1.put("周瑜", "小乔");array.add(hm1);HashMap<String, String> hm2 = new HashMap<>();hm2.put("郭靖", "黄蓉");hm2.put("杨过", "小龙女");array.add(hm2);HashMap<String, String> hm3 = new HashMap<>();hm3.put("孙策3", "大桥3");hm3.put("周瑜3", "小乔3");array.add(hm3);for (HashMap<String,String> hm : array) {Set<String> keySetset = hm.keySet();for (String key : keySetset) {String value = hm.get(key);System.out.println(key + "," + value);}}}}
9.HashMap集合存储ArrayList集合并遍历
需求:创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String,值是ArrayList,每一个ArrayList的元素是String,并遍历
package com.study_05;import java.util.ArrayList;import java.util.HashMap;import java.util.Set;public class HashMapDemo {public static void main(String[] args) {// 创建HashMap集合HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();// 创建ArrayLis集合,并添加元素ArrayList<String> sgyy = new ArrayList<>();sgyy.add("诸葛亮");sgyy.add("赵云");// 把ArrayList作为元素添加到Has和Map集合hm.put("三国演义", sgyy);ArrayList<String> xyj = new ArrayList<>();xyj.add("唐僧");xyj.add("孙悟空");// 把ArrayList作为元素添加到Has和Map集合hm.put("西游记", xyj);ArrayList<String> shz = new ArrayList<>();shz.add("武松");shz.add("鲁智深");// 把ArrayList作为元素添加到Has和Map集合hm.put("水浒传", shz);// 遍历HashMapSet<String> keySet = hm.keySet();for (String key : keySet) {System.out.println(key);ArrayList<String> value = hm.get(key);for (String s : value) {System.out.println("\t"+s);}}}}
10.案例:统计字符串中每个字符出现的次数
需求:键盘录入一个字符串,要求统计字符串中每个字符串出现的次数。
举例:键盘录入“aababcabcdabcde”在控制台输出:“a(5)b(4)c(3)d(2)e(1)”
package com.study_06;import java.util.HashMap;import java.util.Scanner;import java.util.Set;import java.util.TreeMap;public class HashMapDemo {public static void main(String[] args) {// 键盘录入数据Scanner sc = new Scanner(System.in);System.out.print("请输入一个字符串:");String line = sc.nextLine();// 创建HashMap集合,键是Character,值是Integer// HashMap<Character, Integer> hm = new HashMap<>();TreeMap<Character, Integer> hm = new TreeMap<>(); // 按键自然排序// 遍历字符串for (int i = 0; i < line.length(); i++) {char key = line.charAt(i);Integer value = hm.get(key);if (value == null) {// /如果返回值是nulL:说明该字符在HashMap集合中不存在,就把该字符作为键,1作为值存储hm.put(key, 1);} else {// /如果返回值不是nulL:说明该字符在HashMap集合中存在,把该值加1,然后重新存储该事符和对应的值hm.put(key, value + 1);}}//遍历HashMap集合,得到键和值,按照要求进行拼接StringBuilder sb = new StringBuilder();Set<Character> keySet = hm.keySet();for (Character key : keySet) {Integer value = hm.get(key);sb.append(key).append("(").append(value).append(")");}String result = sb.toString();System.out.println(result);}}
11.Collections概述和使用
Collections类的概述
- 是针对集合操作的工具类
Collections类的常用方法
- public static
> void sort(List< T > list):将指定的列表按升序排序 - public static void reverse(List< ?>list):反转指定列表中元素的顺序e
- public static void shuffle(List< ?>list):使用默认的随机源随机排列指定的列表
package com.study_01;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.List;public class CollectionDemo01 {public static void main(String[] args) {// 创建集合对象List<Integer> list = new ArrayList<>();//添加元素list.add(30);list.add(50);list.add(20);list.add(100);// public static<T extends Comparable<?super T>> void sort(List< T > list):将指定的列表按升序排序// Collections.sort(list);// Collections.reverse(list);Collections.shuffle(list);System.out.println(list);}}
package com.study_01;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.Comparator;public class CollectionDemo02 {public static void main(String[] args) {// 创建ArrayList集合对象ArrayList<Student> array = new ArrayList<>();// 创建学生对象Student s1 = new Student("lin",30);Student s2 = new Student("zhang",35);Student s3 = new Student("wang",33);Student s4 = new Student("liu",33);// 把学生添加到集合array.add(s1);array.add(s2);array.add(s3);array.add(s4);//sort (List<T> list,Comparator<? super T>c)Collections.sort(array, new Comparator<Student>() {@Overridepublic int compare(Student s1, Student s2) {int num = s1.getAge() - s2.getAge();int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;return num2;}});for (Student s : array) {System.out.println(s);}}}
package com.study_01;public class Student {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}public Student() {}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;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}}
12.ArrayList学生案例并排序
Collections.sort(array, new Comparator<Student>() {@Overridepublic int compare(Student s1, Student s2) {int num = s1.getAge() - s2.getAge();int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;return num2;}});
13.模拟斗地主
需求:通过程序实现斗地主过程中的洗牌,发牌和看牌
package com.study_02;import java.util.ArrayList;import java.util.Collections;public class PokerDemo {public static void main(String[] args) {// 创建牌盒ArrayList<String> array = new ArrayList<>();// 网牌盒里面装牌// 定义花色数组String[] colors = {"♦", "♣", "♠", "♥"};// 定义点数数组String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};for (String color : colors) {for (String number : numbers) {array.add(color + number);}}array.add("大王");array.add("小王");// 洗牌Collections.shuffle(array);// 发牌ArrayList<String> lqxArray = new ArrayList<>();ArrayList<String> lyArray = new ArrayList<>();ArrayList<String> fqyArray = new ArrayList<>();ArrayList<String> dpArray = new ArrayList<>(); // 底牌三张for (int i = 0; i < array.size(); i++) {String poker = array.get(i);if (i >= array.size() - 3) {dpArray.add(poker);} else if (i % 3 == 0) {lqxArray.add(poker);}else if (i % 3 == 1) {lyArray.add(poker);}else if (i % 3 == 2) {fqyArray.add(poker);}}lookPooker("林青霞",lqxArray);lookPooker("柳岩",lyArray);lookPooker("风情杨",fqyArray);lookPooker("底牌",dpArray);}// 看牌的方法public static void lookPooker(String name,ArrayList<String> array) {System.out.println(name + "的牌是:");for (String poker : array) {System.out.print(poker+" ");}System.out.println();}}
14.案例:模拟斗地主升级版
需求:通过程序实现斗地主过程中的洗牌,发牌和看牌。要求:对牌进行排序
package com.study_03;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.TreeSet;public class PokerDemo {public static void main(String[] args) {// 创建hashmap集合,键是编号,值是牌HashMap<Integer, String> hm = new HashMap<>();// 存储编号ArrayList<Integer> array = new ArrayList<>();// 创建花色数组和点数组// 定义花色数组String[] colors = {"♦", "♣", "♠", "♥"};// 定义点数数组String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};int index = 0;for (String number : numbers) {for (String color : colors) {hm.put(index, color + number);array.add(index);index++;}}hm.put(index, "小王");array.add(index);index++;hm.put(index, "大王");array.add(index);// 洗牌(洗的是编号),用Collection的shuffle()方法实现Collections.shuffle(array);// 发牌TreeSet<Integer> lqxSet = new TreeSet<>();TreeSet<Integer> lyxSet = new TreeSet<>();TreeSet<Integer> fqySet = new TreeSet<>();TreeSet<Integer> dpSet = new TreeSet<>();for (int i = 0; i < array.size(); i++) {int x = array.get(i);if (i >= array.size() - 3) {dpSet.add(x);} else if (i % 3 == 0) {lqxSet.add(x);}else if (i % 3 == 1) {lyxSet.add(x);}else if (i % 3 == 2) {fqySet.add(x);}}lookPoker("林青霞",lqxSet,hm);lookPoker("柳岩",lyxSet,hm);lookPoker("风情杨",fqySet,hm);lookPoker("底牌",dpSet,hm);}// 定义方法看牌public static void lookPoker(String name, TreeSet<Integer> ts,HashMap<Integer,String> hm) {System.out.println(name + "的牌是:");for (Integer key : ts) {String poker = hm.get(key);System.out.print(poker+" ");}System.out.println();}}
