JavaSe——集合_Part3

A.Map

l  Map接口概述

•    将键映射到值的对象

•    一个映射不能包含重复的键

•    每个键最多只能映射到一个值

l  Map接口和Collection接口的不同

•    Map是双列的,Collection是单列的

•    Map的键唯一,Collection的子体系Set是唯一的

•    Map集合的数据结构值针对键有效,跟值无关

  Collection集合的数据结构是针对元素有效


package com.core.collection.demo;

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

public class Test {
	public static void main(String[] args) {
		HashMap map = new HashMap();
		map.put("001", "张三");
		map.put("002", "李四");
		map.put("003", "王五");
		map.put("004", "赵六");

		System.out.println(map);
		// {004=赵六, 001=张三, 002=李四, 003=王五}

		boolean b = map.isEmpty();
		System.out.println(b);// false
		// map.clear();
		// b = map.isEmpty();
		// System.out.println(b);//true

		// 删除功能
		String obj = map.remove("003");
		System.out.println(map + "------" + obj);
		// {004=赵六, 001=张三, 002=李四, 003=王五}
		// {004=赵六, 001=张三, 002=李四}------王五
		obj = map.remove("005");
		System.out.println(map + "------" + obj);
		// {004=赵六, 001=张三, 002=李四}------null

		System.out.println(map.containsKey("001"));// true
		System.out.println(map.containsKey("005"));// false
		System.out.println(map.containsValue("张三"));// true
		System.out.println(map.containsValue("王五"));// false

		System.out.println(map.size());// 3

		System.out.println("--------");
		// 获取所有键
		Set keySet = map.keySet();
		for (String s : keySet) {
			System.out.println(s);
		}
		// 004
		// 001
		// 002
		System.out.println("------");
		// 获取所有值
		Collection collection = map.values();
		for (String s : collection) {
			System.out.println(s);
		}
		// 赵六
		// 张三
		// 李四
		System.out.println("------");
		// 根据键获取值
		keySet = map.keySet();
		for (String s : keySet) {
			String v = map.get(s);
			System.out.println(s + "--" + v);
		}
		// 004--赵六
		// 001--张三
		// 002--李四
		System.out.println("------");
		// 根据键值对对象获取键和值
		Set> set = map.entrySet();
		for (Entry entry : set) {
			String key = entry.getKey();
			String value = entry.getValue();
			System.out.println(key + "**" + value);
		}
		// 004**赵六
		// 001**张三
		// 002**李四
	}
}



B.HashMap

演示4个例子:

1)键是String,值是String

2)键是Integer,值是String

3)键是String,值是Student

4)键是Student,值是String


package com.core.collection.demo1;

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

public class Test {
	public static void main(String[] args) {
		// 键是String 值是String
		HashMap hm = new HashMap();
		hm.put("001", "张三");
		hm.put("002", "李四");
		hm.put("003", "王五");
		hm.put("004", "赵六");
		// 遍历
		Set> set = hm.entrySet();
		for (Entry entry : set) {

			String key = entry.getKey();
			String value = entry.getValue();
			System.out.println(key + "--" + value);
		}
		// 004--赵六
		// 001--张三
		// 002--李四
		// 003--王五

	}
}


package com.core.collection.demo1;

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

public class Test2 {
	public static void main(String[] args) {
		// 键是Integer 值是String
		HashMap hm = new HashMap();
		hm.put(14, "赵六");
		hm.put(21, "张三");
		hm.put(13, "王五");
		hm.put(42, "李四");
		// 遍历
		Set> set = hm.entrySet();
		for (Entry entry : set) {

			Integer key = entry.getKey();
			String value = entry.getValue();
			System.out.println(key + "--" + value);
		}
		// 21--张三
		// 42--李四
		// 13--王五
		// 14--赵六

	}
}


package com.core.collection.demo1;

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

public class Test3 {
	public static void main(String[] args) {
		// 键是String 值是Student
		HashMap hm = new HashMap();
		Student s1 = new Student("张三", 17);
		Student s2 = new Student("李四", 47);
		Student s3 = new Student("王五", 22);
		Student s4 = new Student("赵六", 15);
		hm.put("001", s1);
		hm.put("002", s2);
		hm.put("003", s3);
		hm.put("004", s4);

		Set> set = hm.entrySet();
		for (Entry entry : set) {
			String key = entry.getKey();
			Student s = entry.getValue();
			System.out.println(key + "---" + s.getName() + "---" + s.getAge());
		}
		// 004---赵六---15
		// 001---张三---17
		// 002---李四---47
		// 003---王五---22
	}
}

Student类:

package com.core.collection.demo1;

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

	public Student() {
		super();
	}

	public Student(String name, int age) {
		super();
		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
	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;
	}

}


测试类:

package com.core.collection.demo1;

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

public class Test4 {
	public static void main(String[] args) {
		// 键是Student 值是String
		HashMap hm = new HashMap();
		Student s1 = new Student("张三", 17);
		Student s2 = new Student("李四", 47);
		Student s3 = new Student("王五", 22);
		Student s4 = new Student("赵六", 15);
		Student s5 = new Student("赵六", 15);
		hm.put(s1, "001");
		hm.put(s2, "002");
		hm.put(s3, "003");
		hm.put(s4, "004");
		hm.put(s5, "005");

		Set> set = hm.entrySet();
		for (Entry entry : set) {
			Student key = entry.getKey();
			String value = entry.getValue();
			System.out.println(key.getName() + "---" + key.getAge() + "---"
					+ value);
		}
		// 李四---47---002
		// 张三---17---001
		// 王五---22---003
		// 赵六---15---005
	}
}




C.LinkedHashMap

具有可预知的迭代顺序

存储和取出来的顺序。


package com.core.collection.demo2;

import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;

public class Test {
	public static void main(String[] args) {
		LinkedHashMap hm = new LinkedHashMap();
		hm.put("124", "zhangsan");
		hm.put("234", "lisi");
		hm.put("524", "wangwu");
		hm.put("154", "zhaoliu");
		hm.put("154", "zhaoliu");
		hm.put("124", "zhangsan");

		// 遍历

		Set> set = hm.entrySet();
		for (Entry entry : set) {
			String key = entry.getKey();
			String value = entry.getValue();
			System.out.println(key + "---" + value);
		}
		// 124---zhangsan
		// 234---lisi
		// 524---wangwu
		// 154---zhaoliu

	}
}


D.TreeMap


l  TreeMap类概述

•    键是红黑树结构,可以保证键的排序和唯一性

l  TreeMap案例

•    TreeMap

•    TreeMap


package com.core.collection.demo3;

import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class Test {
	// TreeMap 演示键是String 值是String
	public static void main(String[] args) {
		TreeMap tm = new TreeMap();
		tm.put("hello", "你好");
		tm.put("world", "世界");
		tm.put("java", "爪哇");
		tm.put("world", "世界");
		tm.put("hi", "嗨");

		Set> set = tm.entrySet();
		for (Entry entry : set) {
			String key = entry.getKey();
			String value = entry.getValue();
			System.out.println(key + "---" + value);
		}

		// hello---你好
		// hi---嗨
		// java---爪哇
		// world---世界

	}
}


Student类:

package com.core.collection.demo3;


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

	public Student() {
		super();
	}

	public Student(String name, int age) {
		super();
		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
	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;
	}


}


测试类:

package com.core.collection.demo3;

import java.util.Map.Entry;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;

public class Test2 {
	// TreeMap 演示键是Student 值是String
	public static void main(String[] args) {
		TreeMap tm = new TreeMap(
				new Comparator() {

					@Override
					public int compare(Student o1, Student o2) {
						int num = o1.getAge() - o2.getAge();
						int num2 = num == 0 ? o1.getName().compareTo(
								o2.getName()) : num;
						return num2;
					}
				});
		Student s1 = new Student("张三", 15);
		Student s2 = new Student("李四", 25);
		Student s3 = new Student("王五", 19);
		Student s4 = new Student("赵六", 15);

		tm.put(s1, "777");
		// java.lang.ClassCastException 如果不对Student这个类处理,则报错
		// 处理的第一种方式,匿名内部类

		tm.put(s2, "999");
		tm.put(s3, "888");
		tm.put(s4, "666");

		// 遍历
		Set> set = tm.entrySet();
		for (Entry entry : set) {
			Student key = entry.getKey();
			String value = entry.getValue();
			System.out.println(key.getName() + "---" + key.getAge() + "---"
					+ value);
		}
		// 张三---15---777
		// 赵六---15---666
		// 王五---19---888
		// 李四---25---999
	}
}


//貌似第二种让Student类继承compare接口实现compareTo方法,无效、


E.案例:统计字符串中字母的个数

package com.core.collection.demo4;

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

public class Test {

	public static void main(String[] args) {
		// "aababcabcdabcde",获取字符串中每一个字母出现的次数要求结果:a(5)b(4)c(3)d(2)e(1)
		String str = "aababcabcdabcde";
		char[] charArray = str.toCharArray();
		HashMap hm = new HashMap();
		for (int i = 0; i < charArray.length; i++) {
			char c = charArray[i];
			System.out.println(c);
			if (hm.containsKey(c)) {
				Integer count = hm.get(c);
				count++;
				// hm.remove(c);不需要把原来的删除
				hm.put(c, count);
			} else {
				hm.put(c, 1);
			}
		}

		Set> set = hm.entrySet();
		StringBuffer sb = new StringBuffer();
		for (Entry entry : set) {
			Character key = entry.getKey();
			Integer value = entry.getValue();
//			System.out.println(key + "---" + value);
			sb.append(key).append("<").append(value).append(">");
		}
		String result = sb.toString();
		System.out.println("result:"+result);
	}

}


F.HashMap嵌套HashMap

package com.core.collection.demo5;

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

public class Test {

	public static void main(String[] args) {
		// HashMap嵌套HashMap
		// cz 初中
		// 		张三 15
		// 		李四 16
		// gz 高中
		// 		王五 19
		// 		赵六 18
		HashMap czMap = new HashMap();
		HashMap gzMap = new HashMap();
		HashMap> gradeMap = new HashMap>();
		
		czMap.put("张三", "15");
		czMap.put("李四", "16");
		gradeMap.put("cz", czMap);
		
		gzMap.put("王五", "19");
		gzMap.put("赵六", "18");
		gradeMap.put("gz", gzMap);
		
		//遍历
		
		Set>> gradeSet = gradeMap.entrySet();
		for (Entry> entry : gradeSet) {
			String key = entry.getKey();
			HashMap value = entry.getValue();
			System.out.println(key+":");
			Set> studentSet = value.entrySet();
			for (Entry student : studentSet) {
				String name = student.getKey();
				String age = student.getValue();
				System.out.println("\t"+name+"\t"+age);
			}
		}
	}

}




F.HashMap嵌套ArrayList

package com.core.collection.demo5;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class Test2 {

	public static void main(String[] args) {
		// HashMap嵌套ArrayList

		HashMap> bookMap = new HashMap>();

		ArrayList sanguoList = new ArrayList();
		ArrayList shuihuList = new ArrayList();
		ArrayList xiyouList = new ArrayList();

		sanguoList.add("关羽");
		sanguoList.add("张飞");

		shuihuList.add("武松");
		shuihuList.add("宋江");

		xiyouList.add("孙悟空");
		xiyouList.add("唐僧");

		bookMap.put("sg", sanguoList);
		bookMap.put("sh", shuihuList);
		bookMap.put("xy", xiyouList);

		// 遍历

		Set>> entrySet = bookMap.entrySet();
		for (Entry> entry : entrySet) {

			String key = entry.getKey();
			System.out.println(key + ":");
			ArrayList value = entry.getValue();
			for (String str : value) {
				System.out.println("\t" + str);
			}
		}

	}

}

F.ArrayList嵌套HashMap

package com.core.collection.demo5;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class Test3 {

	public static void main(String[] args) {
		// ArrayList嵌套HashMap
		ArrayList> list = new ArrayList>();
		HashMap hm1 = new HashMap();
		HashMap hm2 = new HashMap();
		HashMap hm3 = new HashMap();
		
		hm1.put("郭靖", "黄蓉");
		
		hm2.put("杨过", "小龙女");
		
		hm3.put("唐伯虎", "秋香");
		
		list.add(hm1);
		list.add(hm2);
		list.add(hm3);
		//遍历
		for (HashMap hm : list) {
			
			Set keySet = hm.keySet();
			for (String key : keySet) {
				String value = hm.get(key);
				System.out.println(key+"---"+value);
			}
//			郭靖---黄蓉
//			杨过---小龙女
//			唐伯虎---秋香
		}
	}

}


F.HashMap和Hashtable的区别


package com.core.collection.demo6;

import java.util.HashMap;
import java.util.Hashtable;

public class Test {

	public static void main(String[] args) {
		// HashMap和Hashtable的区别?
		// HashMap:线程不安全,效率高;允许null值和null键
		// HashTable:线程安全,效率低;不允许null值和null键
		// List,Set,Map等接口是否都继承自Map接口?
		// List和Set继承Collection接口,他们本身也是接口
		// 而Map本身是一个顶层接口了
		HashMap map = new HashMap<>();
		Hashtable table = new Hashtable<>();
		map.put(null, null);
//		table.put(null, null);//java.lang.NullPointerException
	}
}


G.Collections工具类


package com.core.collection.demo7;

import java.util.ArrayList;
import java.util.Collections;

public class Test {

	public static void main(String[] args) {

		//  Collections类概述
		// 针对集合操作 的工具类
		//  Collections成员方法
		// public static  void sort(List list)
		// public static  int binarySearch(List list,T key)
		// public static  T max(Collection coll)
		// public static void reverse(List list)
		// public static void shuffle(List list)
		
		ArrayList list = new ArrayList();
		list.add(10);
		list.add(50);
		list.add(24);
		list.add(62);
		list.add(29);
		System.out.println(list);//[10, 50, 24, 62, 29]
		//排序
		Collections.sort(list);
		System.out.println(list);//[10, 24, 29, 50, 62]
		
		//二分查找
		int index = Collections.binarySearch(list, 24);
		System.out.println(index);//1
		index = Collections.binarySearch(list, 241);
		System.out.println(index);//-6
		
		//最大值
		Integer max = Collections.max(list);
		System.out.println(max);//62
		
		//反转
		Collections.reverse(list);
		System.out.println(list);//[62, 50, 29, 24, 10]
		//随机
		Collections.shuffle(list);
		System.out.println(list);
	}
}



H.ArrayList存储自定义对象并排序案例

Student类:
package com.core.collection.demo8;

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

	public Student() {
		super();
	}

	public Student(String name, int age) {
		super();
		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
	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 int compareTo(Student o) {
		// 先依照姓名,姓名一致,按照年龄
		int num = this.getName().compareTo(o.getName());
		int num2 = num == 0 ? (this.getAge() - o.getAge()) : num;
		return num2;
	}

}


测试类:
package com.core.collection.demo8;

import java.util.ArrayList;
import java.util.Collections;

public class Test {

	public static void main(String[] args) {
		// ArrayList存储自定义对象并排序案例

		ArrayList list = new ArrayList();
		Student s1 = new Student("zhangsan", 25);
		Student s2 = new Student("lisi", 12);
		Student s3 = new Student("wangwu", 42);
		Student s4 = new Student("zhaoliu", 35);
		Student s5 = new Student("sunxi", 17);
		Student s6 = new Student("zhangsan", 43);

		list.add(s1);
		list.add(s2);
		list.add(s3);
		list.add(s4);
		list.add(s5);
		list.add(s6);

		for (Student s : list) {
			System.out.println(s.getName() + "--" + s.getAge());
		}
		// 这是没有经过排序的
		// zhangsan--25
		// lisi--12
		// wangwu--42
		// zhaoliu--35
		// sunxi--17
		// zhangsan--43
		Collections.sort(list);
		System.out.println("-----------");
		// 这是经过排序的
		for (Student s : list) {
			System.out.println(s.getName() + "--" + s.getAge());
		}
		// lisi--12
		// sunxi--17
		// wangwu--42
		// zhangsan--25
		// zhangsan--43
		// zhaoliu--35
	}
}



H.斗地主案例


package com.core.collection.demo9;

import java.util.ArrayList;
import java.util.Collections;

public class Test {
	// 模拟斗地主洗牌和发牌
	public static void main(String[] args) {

		String[] colors = { "♥", "♠", "♦", "♣" };
		String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10",
				"J", "Q", "K" };

		ArrayList list = new ArrayList();
		for (String color : colors) {
			for (String number : numbers) {
				StringBuffer sb = new StringBuffer();
				sb.append(color).append(number);
				list.add(sb.toString());
			}
		}
		list.add("小王");
		list.add("大王");
		
		System.out.println(list);
		
		// 创建4个选手
		ArrayList p1 = new ArrayList();
		ArrayList p2 = new ArrayList();
		ArrayList p3 = new ArrayList();
		ArrayList dipai = new ArrayList();
		// 洗牌
		Collections.shuffle(list);
		// 发牌
		for (int i = 0; i < list.size(); i++) {
			if (i > list.size() - 4) {
				dipai.add(list.get(i));
			} else if (i % 3 == 0) {
				p1.add(list.get(i));
			} else if (i % 3 == 1) {
				p2.add(list.get(i));
			} else if (i % 3 == 2) {
				p3.add(list.get(i));
			}
		}
		//看牌
		lookPoker("p1",p1);
		lookPoker("p2",p2);
		lookPoker("p3",p3);
		lookPoker("dipai",dipai);
	}

	private static void lookPoker(String string, ArrayList p1) {
		System.out.print(string+"的牌是:");
		for (String str : p1) {
			System.out.print(str+",");
		}
		System.out.println();
	}
}

p1的牌是:♣4,♠Q,♠A,♦J,♥Q,♦10,♣Q,♦8,小王,♦Q,♦4,♠10,大王,♦9,♥5,♠7,♣10,
p2的牌是:♥J,♣6,♠J,♠3,♦3,♦2,♣K,♥2,♣A,♥4,♠6,♠9,♠5,♠8,♠K,♥3,♦K,
p3的牌是:♦6,♥A,♦A,♥9,♣8,♣7,♥7,♣5,♣2,♦7,♥6,♣3,♠4,♣9,♠2,♣J,♥8,
dipai的牌是:♥K,♥10,♦5,

对牌排序:


package com.core.collection.demo10;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;

public class Test {
	// 模拟斗地主洗牌和发牌
	public static void main(String[] args) {

		String[] colors = { "♥", "♠", "♦", "♣" };
		String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10",
				"J", "Q", "K" };

		ArrayList list = new ArrayList();
		HashMap hm = new HashMap();
		int count = 0;

		for (String number : numbers) {
			for (String color : colors) {
				StringBuffer sb = new StringBuffer();
				sb.append(color).append(number);
				list.add(count);
				hm.put(count, sb.toString());
				count++;
			}
		}
		count++;
		list.add(count);
		hm.put(count, "小王");
		count++;
		list.add(count);
		hm.put(count, "大王");

		System.out.println(list);

		// 创建4个选手
		TreeSet set1 = new TreeSet();
		TreeSet set2 = new TreeSet();
		TreeSet set3 = new TreeSet();
		TreeSet diPaiSet = new TreeSet();
		// 洗牌
		Collections.shuffle(list);
		// 发牌
		for (int i = 0; i < list.size(); i++) {
			if (i > list.size() - 4) {
				diPaiSet.add(list.get(i));
			} else if (i % 3 == 0) {
				set1.add(list.get(i));
			} else if (i % 3 == 1) {
				set2.add(list.get(i));
			} else if (i % 3 == 2) {
				set3.add(list.get(i));
			}
		}
		// 看牌
		lookPoker("p1", set1, hm);
		lookPoker("p2", set2, hm);
		lookPoker("p3", set3, hm);
		lookPoker("dipai", diPaiSet, hm);
	}

	private static void lookPoker(String string, TreeSet set,
			HashMap hm) {
		System.out.print(string + "的牌是:");
		Iterator iterator = set.iterator();
		while (iterator.hasNext()) {
			Integer next = iterator.next();
			String result = hm.get(next);
			System.out.print(result + ",");
		}
		System.out.println();
	}

}


p1的牌是:♥2,♣2,♠3,♥4,♦4,♠5,♦5,♠6,♣6,♠8,♦8,♠9,♥10,♥Q,♠K,♦K,大王,
p2的牌是:♠A,♣A,♥3,♠4,♣4,♣5,♥7,♠7,♦7,♣7,♣8,♥9,♦9,♣9,♣10,♠J,小王,
p3的牌是:♥A,♠2,♦2,♦3,♣3,♥5,♥6,♦6,♥8,♠10,♦10,♥J,♠Q,♦Q,♣Q,♥K,♣K,
dipai的牌是:♦A,♦J,♣J,






你可能感兴趣的:(JavaSe——集合_Part3)