黑马JAVA P138 Map集合案例、其他实现类

 

package com.itheima.d8_map_test;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 需求:统计投票人数
 */
public class MapTest1 {
    public static void main(String[] args) {
        //1.把88个学生选择的数据拿进来。
        String[] selects = {"A", "B", "C", "D"};
        StringBuilder sb = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i < 80 ; i++) {
            sb.append(selects[r.nextInt(selects.length)]);
        }
        
        System.out.println(sb);

        //2、定义一个Map集合记录最终统计的结果:A=30  B=20 C=20 D=10
        Map<Character,Integer> infos = new HashMap<>();
        
        //3.遍历80个学生选择的数据
        for (int i = 0; i < sb.length(); i++) {
            //4.提取当前选择经典字符
            char ch = sb.charAt(i);
            //5.判断Map集合中是否存在这个键
            if(infos.containsKey(ch)){
                //让其值+1
                infos.put(ch ,infos.get(ch) + 1);
            }else{
                //说明此景点第一次被选
                infos.put(ch , 1);
            }
        }

        System.out.println(infos);
    }
}

 


 

 

 

 

package com.itheima.d9_map_impl;

import com.itheima.d1_set.Student;

import java.util.HashMap;
import java.util.Map;

public class HashMapDemo1 {
    public static void main(String[] args) {
        //Map集合是根据键去除重复元素
        Map<Student, String> maps = new HashMap<>();
        Student s1 = new Student("无恙",20,'男');
        Student s2 = new Student("无恙",20,'男');
        Student s3 = new Student("周雄",22,'男');

        maps.put(s1,"北京");
        maps.put(s2,"上海");
        maps.put(s3,"广州");

        System.out.println(maps);
    }
}

 


 


 

 

 

 

package com.itheima.d9_map_impl;

import com.itheima.d1_set.Apple;

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

public class TreeMapDemo3 {
    public static void main(String[] args) {
        Map<Integer, String> maps1 = new TreeMap<>();
        maps1.put(13,"王麻子");
        maps1.put(1,"张兰");
        maps1.put(3,"县长");
        System.out.println(maps1);

        //TreeMap 集合自带排序。 可排序  不重复(只要大小规则一样就认为重复)  无索引
        Map<Apple, String> maps2 = new TreeMap<>(new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2) {
                return Double.compare(o2.getPrice() , o1.getPrice()); //按照价格降序升序!
            }
        });
        maps2.put(new Apple("红富士","红色",9.9,500),"山东");
        maps2.put(new Apple("绿富士","绿色",8.9,400),"福建");
        maps2.put(new Apple("黄富士","黄色",7.9,300),"广西");
        maps2.put(new Apple("橙富士","橙色",6.9,500),"上海");

        System.out.println(maps2);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值