Java--集合框架--Map集合、 HashMap和Hashtable的区别、 Collections(集合工具类)

Map集合
HashMap和Hashtable的区别
Collections(集合工具类)
集合练习
模拟斗地主(洗牌,发牌,看牌)

集合框架(Map集合概述和特点)

A: 需求:	根据学号获取学生姓名
public class MyTest {
    public static void main(String[] args) {
        ArrayList<String> list= new ArrayList<>();
        list.add("s001------张三");
        list.add("s002------李四");
        list.add("s003------王五");
        list.add("s004------赵六");

        String s = list.get(0);
        String[] strings = s.split("[-]+");
        System.out.println(strings[0]);
        System.out.println(strings[1]);

    }
}

B:Map接口概述
	查看API可以知道:
	将键映射到值的对象
	一个映射不能包含重复的键
	每个键最多只能映射到一个值
C:Map接口和Collection接口的不同
	Map是双列的,Collection是单列的
	Map的键唯一,Collection的子体系Set是唯一的
	Map集合的数据结构针对键有效,跟值无关;Collection集合的数据结构是针对元素有效

集合框架(Map集合的功能概述)

A:Map集合的功能概述
	a:添加功能 
		V put(K key,V value):添加元素。这个其实还有另一个功能?替换
			如果键是第一次存储,就直接存储元素,返回null
			如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值
	b:删除功能
		void clear():移除所有的键值对元素
		V remove(Object key):根据键删除键值对元素,并把值返回
	c:判断功能
		boolean containsKey(Object key):判断集合是否包含指定的键
		boolean containsValue(Object value):判断集合是否包含指定的值
		boolean isEmpty():判断集合是否为空
	d:获取功能
		Set<Map.Entry<K,V>> entrySet(): 返回一个键值对的Set集合
		V get(Object key):根据键获取值
		Set<K> keySet():获取集合中所有键的集合
		Collection<V> values():获取集合中所有值的集合
	e:长度功能
		int size():返回集合中的键值对的对数

集合框架(Map集合的基本功能测试)

A:案例演示
Map集合的基本功能:
	V put(K key,V value)  
	V remove(Object key)
	void clear()
	boolean containsKey(Object key)
	boolean containsValue(Object value)
	boolean isEmpty()
	int size()
	
public class MyTest {
    public static void main(String[] args) {
        HashMap<String, String> hm = new HashMap<>();

        String s = hm.put("文章", "马伊琍");
        hm.put("贾乃亮","李小璐");
        hm.put("王宝强","马蓉");
        hm.put("陈羽凡","白百何");
        hm.put("王大治","董洁");
        hm.put("武大郎","潘金莲");

        hm.remove("武大郎");
       // hm.clear();

        System.out.println(hm);
        boolean empty = hm.isEmpty();
        int size = hm.size();

        System.out.println(hm.containsKey("贾乃亮"));
        System.out.println(hm.containsValue("潘金莲"));
    }
}

集合框架(Map集合的获取功能测试)

A:案例演示
V get(Object key)
	Set<K> keySet()
	Collection<V> values()

public class MyTest {
    public static void main(String[] args) {
        HashMap<String, String> hm = new HashMap<>();

        String s = hm.put("文章", "马伊琍");
        hm.put("贾乃亮","李小璐");
        hm.put("王宝强","马蓉");
        hm.put("陈羽凡","白百何");
        hm.put("王大治","董洁");
        hm.put("武大郎","潘金莲");

        String value = hm.get("文章");
        System.out.println(value);

        Set<String> strings = hm.keySet();
        for (String string : strings) {
            System.out.println(string+"=="+hm.get(string));
        }

        Collection<String> values = hm.values();
        System.out.println(values);        
    }
}

集合框架(Map集合的遍历之键找值)

A:键找值思路:
	获取所有键的集合
	遍历键的集合,获取到每一个键
	根据键找值
B:案例演示
	Map集合的遍历之键找值
public class MyTest {
    public static void main(String[] args) {
        HashMap<String, String> hm = new HashMap<>();

        String s = hm.put("文章", "马伊琍");
        hm.put("贾乃亮","李小璐");
        hm.put("王宝强","马蓉");
        hm.put("陈羽凡","白百何");
        hm.put("王大治","董洁");
        hm.put("武大郎","潘金莲");

        Set<Map.Entry<String, String>> entries = hm.entrySet();
        for (Map.Entry<String, String> entry : entries)       {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"=="+value);
        }
    }
}

集合框架(Map集合的遍历之键值对对象找键和值)

A:键值对对象找键和值思路:
	获取所有键值对对象的集合
	遍历键值对对象的集合,获取到每一个键值对对象
	根据键值对对象找键和值
B:案例演示
	Map集合的遍历之键值对对象找键和值
public class MyTest {
    public static void main(String[] args) {
        HashMap<String, Student> hashMap = new HashMap<>();
        hashMap.put("s001",new Student("张三",23));
        hashMap.put("s002",new Student("张三",23));
        hashMap.put("s003",new Student("李四",21));
        hashMap.put("s004",new Student("王五",18));
        hashMap.put("s005",new Student("赵六",20));
        hashMap.put("s006",new Student("田七",17));

        Set<String> strings = hashMap.keySet();
        for (String string : strings) {
            Student student = hashMap.get(string);
            System.out.println(string+"=="+student.getName()+"=="+student.getAge());

        }

        Set<Map.Entry<String, Student>> entries = hashMap.entrySet();
        for (Map.Entry<String, Student> entry : entries) {
            String key = entry.getKey();
            Student value = entry.getValue();
            System.out.println(key+"=="+value);
        }
    }
}

集合框架(HashMap集合键是Stirng值是String的案例)(掌握)

​HashMap	允许插入null键 null值
A:案例演示:	HashMap集合键是Stirng值是String的案例
public class MyTest {
    public static void main(String[] args) {
        HashMap<String, String> hm = new HashMap<>();
        String s = hm.put("文章", "马伊琍");
        System.out.println(s);
        String s1 = hm.put("文章", "姚笛");
        System.out.println(s1);
        hm.put("贾乃亮","李小璐");
        hm.put("王宝强","马蓉");
        hm.put("陈羽凡","白百何");
        hm.put("王大治","董洁");
        hm.put("武大郎","潘金莲");

        System.out.println(hm);
    }
}

集合框架(HashMap集合键是String值是Student的案例)

A:案例演示:	HashMap集合键是String值是Student的案例
public class MyTest {
    public static void main(String[] args) {
        HashMap<String, Student> hashMap = new HashMap<>();
        hashMap.put("s001",new Student("张三",23));
        hashMap.put("s002",new Student("张三",23));
        hashMap.put("s003",new Student("李四",21));
        hashMap.put("s004",new Student("王五",18));
        hashMap.put("s005",new Student("赵六",20));
        hashMap.put("s006",new Student("田七",17));

        System.out.println(hashMap);
    }
}

集合框架(HashMap集合键是Student值是String的案例)

键唯一  注意重写hashCode方法 和  equals 方法
A:案例演示:	HashMap集合键是Student值是String的案例

集合框架(LinkedHashMap的概述和使用)

A:LinkedHashMap的概述:	Map 接口的哈希表和链接列表实现,具有可预知的迭代顺序
B:LinkedHashMap的特点: 底层的数据结构是链表和哈希表 元素有序 并且唯一
			元素的有序性由链表数据结构保证 唯一性由 哈希表数据结构保证
			Map集合的数据结构只和键有关
C:案例演示:	LinkedHashMap的特点
public class MyTest {
    public static void main(String[] args) {
        LinkedHashMap<String, String> map= new LinkedHashMap<>();
        map.put("文章", "马伊琍");
        map.put("贾乃亮","李小璐");
        map.put("王宝强","马蓉");
        map.put("陈羽凡","白百何");
        map.put("王大治","董洁");
        map.put("武大郎","潘金莲");

        map.forEach(new BiConsumer<String, String>() {
            @Override
            public void accept(String key, String value) {
                System.out.println(key+"=="+value);
            }
        });
    }
}

集合框架(TreeMap集合键是String值是String的案例)

​	TreeMap 键不允许插入null
A: TreeMap: 键的数据结构是红黑树,可保证键的排序和唯一性  
	    排序分为自然排序和比较器排序 
	    线程是不安全的效率比较高
B:案例演示:	TreeMap集合键是Integer值是String的案例
public class TreeMapDemo {
    public static void main(String[] args) {
        TreeMap<Integer, String> treeMap = new TreeMap<>();
        treeMap.put(1,"aaa");
        treeMap.put(18,"ccc");
        treeMap.put(23,"ddd");
        treeMap.put(4,"ooo");
        treeMap.put(85,"kkk");

        treeMap.forEach(new BiConsumer<Integer, String>() {
            @Override
            public void accept(Integer key, String s) {
                System.out.println(key);
            }
        });

    }
}

集合框架(TreeMap集合键是Student值是String的案例)

A:案例演示:	TreeMap集合键是Student值是String的案例
		按照年龄大小进行排序 
		注意键要实现Comparable 接口
public class MyTest {
    public static void main(String[] args) {
        TreeMap<Student, String> treeMap = new TreeMap<>();
        treeMap.put(new Student("张三",20),"s001");
        treeMap.put(new Student("张三2",19),"s002");
        treeMap.put(new Student("李四",22),"s003");
        treeMap.put(new Student("王五",18),"s004");
        treeMap.put(new Student("赵六",21),"s005");
        treeMap.put(new Student("田七",23),"s006");
        treeMap.put(new Student("一一",18),"s007");

       //System.out.println(treeMap);

        treeMap.forEach(new BiConsumer<Student, String>() {
            @Override
            public void accept(Student student, String s) {
                System.out.println(student.getName()+"=="+student.getAge());
            }
        });
    }
}

集合框架(统计字符串中每个字符出现的次数)

A:案例演示:	需求:统计字符串中每个字符出现的次数
	"aababcabcdabcde",获取字符串中每一个字母出现的次数要求结果:a(5)b(4)c(3)d(2)e(1)
public class MyTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一段字符串");
        String str = sc.nextLine();

        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (!map.containsKey(ch)){
                map.put(ch,1);
            }else {
                Integer integer = map.get(ch);
                integer++;
                map.put(ch,integer);
            }
        }
        StringBuilder sb = new StringBuilder();
        map.forEach(new BiConsumer<Character, Integer>() {
            @Override
            public void accept(Character character, Integer integer) {
                sb.append(character).append("(").append(integer).append(")");
                
            }
        });
        String string = sb.toString();
        System.out.println(string);
    }
}

集合框架(集合嵌套之HashMap嵌套HashMap)

A:案例演示
	集合嵌套之HashMap嵌套HashMap
	       基础班
​					张三		20
​					李四		22
​				就业班
​					王五		21
​					赵六		23

public class MyTest {
    public static void main(String[] args) {
        HashMap<String, Integer> jcMap = new HashMap<>();
        jcMap.put("张三",20);
        jcMap.put("李四",22);

        HashMap<String, Integer> jyMap = new HashMap<>();
        jyMap.put("王五",21);
        jyMap.put("赵六",23);

        HashMap<String, HashMap<String, Integer>> maxMap = new HashMap<>();
        maxMap.put("基础班",jcMap);
        maxMap.put("就业班",jyMap);

        Set<String> strings = maxMap.keySet();
        for (String string : strings) {
            System.out.println(string);
            HashMap<String, Integer> stringIntegerHashMap = maxMap.get(string);
            Set<String> strings1 = stringIntegerHashMap.keySet();
            for (String s : strings1) {
                System.out.println("\t"+s+"\t"+stringIntegerHashMap.get(s));
            }
            System.out.println();
        }

    }
}

集合框架(集合嵌套之HashMap嵌套ArrayList)

A:案例演示
	集合嵌套之HashMap嵌套ArrayList
		
	假设HashMap集合的元素是ArrayList。有3个。
	每一个ArrayList集合的值是字符串。

	三国演义
	 	吕布
	 	周瑜
	 笑傲江湖
	 	令狐冲
	 	林平之
	 神雕侠侣
	 	郭靖
	 	杨过  

public class MyTest {
    public static void main(String[] args) {
        ArrayList<String> sgList = new ArrayList<>();
        sgList.add("吕布");
        sgList.add("周瑜");

        ArrayList<String> xaList = new ArrayList<>();
        xaList.add("令狐冲");
        xaList.add("林平之");

        ArrayList<String> sdList = new ArrayList<>();
        sdList.add("尹志平");
        sdList.add("郭靖");

        HashMap<String, ArrayList<String>> maxMap = new HashMap<>();
        maxMap.put("三国演义",sgList);
        maxMap.put("笑傲江湖",xaList);
        maxMap.put("神雕侠侣",sdList);

        Set<Map.Entry<String, ArrayList<String>>> entries = maxMap.entrySet();
        for (Map.Entry<String, ArrayList<String>> entry : entries) {
            String key = entry.getKey();
            System.out.println(key);
            ArrayList<String> list = entry.getValue();
            for (String s : list) {
                System.out.println("\t"+s);
            }
            System.out.println();
        }
    }
}

集合框架(集合嵌套之ArrayList嵌套HashMap)

A:案例演示
	集合嵌套之ArrayList嵌套HashMap
	
	假设ArrayList集合的元素是HashMap。有3个。
	每一个HashMap集合的键和值都是字符串。

	 周瑜---小乔
	 吕布---貂蝉

	 郭靖---黄蓉
	 杨过---小龙女

	 令狐冲---任盈盈
	 林平之---岳灵珊

public class MyTest {
    public static void main(String[] args) {
        HashMap<String, String> sgmap = new HashMap<>();
        sgmap.put("周瑜","小乔");
        sgmap.put("吕布","貂蝉");

        HashMap<String, String> sdmap = new HashMap<>();
        sdmap.put("郭靖","黄蓉");
        sdmap.put("杨过","小龙女");
        sdmap.put("杨过","郭襄");

        HashMap<String, String> xamap = new HashMap<>();
        xamap.put("令狐冲","任盈盈");
        xamap.put("林平之","岳灵珊");

        ArrayList<HashMap<String, String>> maxList = new ArrayList<>();
        maxList.add(sgmap);
        maxList.add(sdmap);
        maxList.add(xamap);

        for (HashMap<String, String> map : maxList) {
            Set<Map.Entry<String, String>> entries = map.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String key = entry.getKey();
                String value = entry.getValue();
                System.out.println(key+"--"+value);
            }
            System.out.println();
        }
    }
}

集合框架(HashMap和Hashtable的区别)

A:HashMap和Hashtable的区别:	
	HashMap: 线程不安全,效率高.允许null值和null键
	Hashtable: 线程安全 , 效率低.不允许null值和null键
B:案例演示	
	HashMap和Hashtable的区别
public class MyTest5 {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put(null,null);
        System.out.println(map);

       /* Hashtable<Object, Object> objectObjectHashtable = new Hashtable<>();
        objectObjectHashtable.put(null,null);*/
    }
}

集合框架(Collections工具类的概述和常见方法讲解)

A:Collections类概述:	针对集合操作 的工具类
B:Collections成员方法
	public static <T> void sort(List<T> list):					排序,默认按照自然顺序
	public static <T> int binarySearch(List<?> list,T key):		二分查找
	public static <T> T max(Collection<?> coll):				获取最大值
	public static void reverse(List<?> list):					反转
	public static void shuffle(List<?> list):						随机置换
C:案例演示:	Collections工具类的常见方法讲解
public class MyTest {
    public static void main(String[] args) {
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(20);
        integers.add(27);
        integers.add(40);
        integers.add(100);
        int i = Collections.binarySearch(integers, 20);
        System.out.println(i);

        Collections.sort(integers, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return 0;
            }
        });

        Integer max = Collections.max(integers);
        System.out.println(max);
        Integer min = Collections.min(integers);
        System.out.println(min);

        Collections.shuffle(integers);
        System.out.println(integers);
    }
}

集合框架(模拟斗地主洗牌和发牌)

A:案例演示:	模拟斗地主洗牌和发牌,牌没有排序
public class MyTest {
    public static void main(String[] args) {
        ArrayList<String> pokerBox = new ArrayList<>();
        String[] colors={"♥","♠","♣","♦"};
        String[] num={"A","1","2","3","4","5","6","7","8","9","10","J","Q","K"};
        for (String color : colors) {
            for (String s : num) {
                pokerBox.add(color.concat(s));
            }
        }
        pokerBox.add("☀");
        pokerBox.add("🌙");

        Collections.shuffle(pokerBox);
        Collections.shuffle(pokerBox);
        Collections.shuffle(pokerBox);

        ArrayList<String> aa = new ArrayList<>();
        ArrayList<String> bb = new ArrayList<>();
        ArrayList<String> cc = new ArrayList<>();
        ArrayList<String> dd = new ArrayList<>();

        for (int i = 0; i < pokerBox.size(); i++) {
            if (i>=pokerBox.size()-3){
                dd.add(pokerBox.get(i));
            }else if(i%3==0){
                aa.add(pokerBox.get(i));
            }else if(i%3==1){
                bb.add(pokerBox.get(i));
            }else {
                cc.add(pokerBox.get(i));
            }
        }

        lookPoker("aa",aa);
        lookPoker("bb",bb);
        lookPoker("cc",cc);
        lookPoker("dd",dd);
    }

    private static void lookPoker(String name, ArrayList<String> list) {
        System.out.println(name);
        for (String s : list) {
            System.out.print(s+"\t");
        }
        System.out.println();
    }
}

集合框架(模拟斗地主洗牌和发牌并对牌进行排序的代码实现)

A:案例演示:	模拟斗地主洗牌和发牌并对牌进行排序的代码实现
public class MyTest {
    public static void main(String[] args) {
        HashMap<Integer, String> pokerBox = new HashMap<>();
        String[] colors={"♥","♠","♣","♦"};
        String[] num={"A","1","2","3","4","5","6","7","8","9","10","J","Q","K"};

        ArrayList<Integer> indexs = new ArrayList<>();
        int index=0;
        for (String s : num) {
            for (String color : colors) {
                pokerBox.put(index,s.concat(color));
                indexs.add(index);
                index++;
            }
        }
        pokerBox.put(index,"☀");
        indexs.add(index);
        index++;
        pokerBox.put(index,"🌙");

        Collections.shuffle(indexs);
        Collections.shuffle(indexs);
        Collections.shuffle(indexs);

        TreeSet<Integer> ee = new TreeSet<>();
        TreeSet<Integer> ff= new TreeSet<>();
        TreeSet<Integer> hh = new TreeSet<>();
        TreeSet<Integer> dd = new TreeSet<>();

        for (int i = 0; i < indexs.size(); i++) {
            if (i>=indexs.size()-3){
                dd.add(indexs.get(i));
            }else if(i%3==0){
                ee.add(indexs.get(i));
            }else if(i%3==1){
                ff.add(indexs.get(i));
            }else {
                hh.add(indexs.get(i));
            }
        }

        lookPoker("ee",ee,pokerBox);
        lookPoker("ff",ff,pokerBox);
        lookPoker("hh",hh,pokerBox);
        lookPoker("dd",dd,pokerBox);
    }

    private static void lookPoker(String name, TreeSet<Integer> set, HashMap<Integer, String> pokerBox) {
        System.out.println(name);
        for (Integer key : set) {
            String s = pokerBox.get(key);
            System.out.print(s+"\t");
        }
        System.out.println();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值