集合案例练习

来源:互联网 发布:生成对抗网络 用途 编辑:程序博客网 时间:2024/06/06 18:28

A:统计一个字符串中每个字符出现的次数

/* * 需求 :"aababcabcdabcde",获取字符串中每一个字母出现的次数要求结果:a(5)b(4)c(3)d(2)e(1) *  * 分析: *      A:定义一个字符串(可以改进为键盘录入) *      B:定义一个TreeMap集合 *          键:Character *          值:Integer *      C:把字符串转换为字符数组 *      D:遍历字符数组,得到每一个字符 *      E:拿刚才得到的字符作为键到集合中去找值,看返回值 *          是null:说明该键不存在,就把该字符作为键,1作为值存储 *          不是null:说明该键存在,就把值加1,然后重写存储该键和值 *      F:定义字符串缓冲区变量 *      G:遍历集合,得到键和值,进行按照要求拼接 *      H:把字符串缓冲区转换为字符串输出 *  * 录入:linqingxia * 结果:result:a(1)g(1)i(3)l(1)n(2)q(1)x(1) */public class TreeMapDemo {    public static void main(String[] args) {        // 定义一个字符串(可以改进为键盘录入)        Scanner sc = new Scanner(System.in);        System.out.println("请输入一个字符串:");        String line = sc.nextLine();        // 定义一个TreeMap集合        TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();        //把字符串转换为字符数组        char[] chs = line.toCharArray();        //遍历字符数组,得到每一个字符        for(char ch : chs){            //拿刚才得到的字符作为键到集合中去找值,看返回值            Integer i =  tm.get(ch);            //是null:说明该键不存在,就把该字符作为键,1作为值存储            if(i == null){                tm.put(ch, 1);            }else {                //不是null:说明该键存在,就把值加1,然后重写存储该键和值                i++;                tm.put(ch,i);            }        }        //定义字符串缓冲区变量        StringBuilder sb=  new StringBuilder();        //遍历集合,得到键和值,进行按照要求拼接        Set<Character> set = tm.keySet();        for(Character key : set){            Integer value = tm.get(key);            sb.append(key).append("(").append(value).append(")");        }        //把字符串缓冲区转换为字符串输出        String result = sb.toString();        System.out.println("result:"+result);    }}

B:集合的嵌套遍历
a:HashMap嵌套HashMap

/* * HashMap嵌套HashMap *  * 培训学校 *      jc  基础班 *              陈玉楼     20 *              高跃      22 *      jy  就业班 *              李杰      21 *              曹石磊     23 *  * 先存储元素,然后遍历元素 */public class HashMapDemo2 {    public static void main(String[] args) {        // 创建集合对象        HashMap<String, HashMap<String, Integer>> czbkMap = new HashMap<String, HashMap<String, Integer>>();        // 创建基础班集合对象        HashMap<String, Integer> jcMap = new HashMap<String, Integer>();        // 添加元素        jcMap.put("陈玉楼", 20);        jcMap.put("高跃", 22);        // 把基础班添加到大集合        czbkMap.put("jc", jcMap);        // 创建就业班集合对象        HashMap<String, Integer> jyMap = new HashMap<String, Integer>();        // 添加元素        jyMap.put("李杰", 21);        jyMap.put("曹石磊", 23);        // 把基础班添加到大集合        czbkMap.put("jy", jyMap);        //遍历集合        Set<String> czbkMapSet = czbkMap.keySet();        for(String czbkMapKey : czbkMapSet){            System.out.println(czbkMapKey);            HashMap<String, Integer> czbkMapValue = czbkMap.get(czbkMapKey);            Set<String> czbkMapValueSet = czbkMapValue.keySet();            for(String czbkMapValueKey : czbkMapValueSet){                Integer czbkMapValueValue = czbkMapValue.get(czbkMapValueKey);                System.out.println("\t"+czbkMapValueKey+"---"+czbkMapValueValue);            }        }    }}
        b:HashMap嵌套ArrayList
/* *需求: *假设HashMap集合的元素是ArrayList。有3个。 *每一个ArrayList集合的值是字符串。 *元素我已经完成,请遍历。 *结果: *       三国演义 *          吕布 *          周瑜 *       笑傲江湖 *          令狐冲 *          林平之 *       神雕侠侣 *          郭靖 *          杨过   */public class HashMapIncludeArrayListDemo {    public static void main(String[] args) {        // 创建集合对象        HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();        // 创建元素集合1        ArrayList<String> array1 = new ArrayList<String>();        array1.add("吕布");        array1.add("周瑜");        hm.put("三国演义", array1);        // 创建元素集合2        ArrayList<String> array2 = new ArrayList<String>();        array2.add("令狐冲");        array2.add("林平之");        hm.put("笑傲江湖", array2);        // 创建元素集合3        ArrayList<String> array3 = new ArrayList<String>();        array3.add("郭靖");        array3.add("杨过");        hm.put("神雕侠侣", array3);        //遍历集合        Set<String> set = hm.keySet();        for(String key : set){            System.out.println(key);            ArrayList<String> value = hm.get(key);            for(String s : value){                System.out.println("\t"+s);            }        }    }}
        c:ArrayList嵌套HashMap
/* ArrayList集合嵌套HashMap集合并遍历。 需求: 假设ArrayList集合的元素是HashMap。有3个。 每一个HashMap集合的键和值都是字符串。 元素我已经完成,请遍历。 结果: 周瑜---小乔 吕布---貂蝉 郭靖---黄蓉 杨过---小龙女 令狐冲---任盈盈 林平之---岳灵珊 */public class ArrayListIncludeHashMapDemo {    public static void main(String[] args) {        // 创建集合对象        ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>();        // 创建元素1        HashMap<String, String> hm1 = new HashMap<String, String>();        hm1.put("周瑜", "小乔");        hm1.put("吕布", "貂蝉");        // 把元素添加到array里面        array.add(hm1);        // 创建元素1        HashMap<String, String> hm2 = new HashMap<String, String>();        hm2.put("郭靖", "黄蓉");        hm2.put("杨过", "小龙女");        // 把元素添加到array里面        array.add(hm2);        // 创建元素1        HashMap<String, String> hm3 = new HashMap<String, String>();        hm3.put("令狐冲", "任盈盈");        hm3.put("林平之", "岳灵珊");        // 把元素添加到array里面        array.add(hm3);        // 遍历        for (HashMap<String, String> hm : array) {            Set<String> set = hm.keySet();            for (String key : set) {                String value = hm.get(key);                System.out.println(key + "---" + value);            }        }    }}
        d:多层嵌套
/* * 为了更符合要求: *      这次的数据就看成是学生对象。 *  * 培训学校 *      bj  北京校区 *          jc  基础班 *                  林青霞     27 *                  风清扬     30 *          jy  就业班  *                  赵雅芝     28 *                  武鑫      29 *      sh  上海校区 *          jc  基础班 *                  郭美美     20 *                  犀利哥     22 *          jy  就业班  *                  罗玉凤     21 *                  马征      23 *      gz  广州校区 *          jc  基础班 *                  王力宏     30 *                  李静磊     32 *          jy  就业班  *                  郎朗      31 *                  柳岩      33 *      xa  西安校区 *          jc  基础班 *                  范冰冰     27 *                  刘意      30 *          jy  就业班  *                  李冰冰     28 *                  张志豪     29 */public class HashMapDemo {    public static void main(String[] args) {        // 创建大集合        HashMap<String, HashMap<String, ArrayList<Student>>> czbkMap = new HashMap<String, HashMap<String, ArrayList<Student>>>();        // 北京校区数据        HashMap<String, ArrayList<Student>> bjCzbkMap = new HashMap<String, ArrayList<Student>>();        ArrayList<Student> array1 = new ArrayList<Student>();        Student s1 = new Student("林青霞", 27);        Student s2 = new Student("风清扬", 30);        array1.add(s1);        array1.add(s2);        ArrayList<Student> array2 = new ArrayList<Student>();        Student s3 = new Student("赵雅芝", 28);        Student s4 = new Student("武鑫", 29);        array2.add(s3);        array2.add(s4);        bjCzbkMap.put("基础班", array1);        bjCzbkMap.put("就业班", array2);        czbkMap.put("北京校区", bjCzbkMap);        // 晚上可以自己练习一下        // 上海校区数据自己做        // 广州校区数据自己做        // 西安校区数据        HashMap<String, ArrayList<Student>> xaCzbkMap = new HashMap<String, ArrayList<Student>>();        ArrayList<Student> array3 = new ArrayList<Student>();        Student s5 = new Student("范冰冰", 27);        Student s6 = new Student("刘意", 30);        array3.add(s5);        array3.add(s6);        ArrayList<Student> array4 = new ArrayList<Student>();        Student s7 = new Student("李冰冰", 28);        Student s8 = new Student("张志豪", 29);        array4.add(s7);        array4.add(s8);        xaCzbkMap.put("基础班", array3);        xaCzbkMap.put("就业班", array4);        czbkMap.put("西安校区", xaCzbkMap);        // 遍历集合        Set<String> czbkMapSet = czbkMap.keySet();        for (String czbkMapKey : czbkMapSet) {            System.out.println(czbkMapKey);            HashMap<String, ArrayList<Student>> czbkMapValue = czbkMap                    .get(czbkMapKey);            Set<String> czbkMapValueSet = czbkMapValue.keySet();            for (String czbkMapValueKey : czbkMapValueSet) {                System.out.println("\t" + czbkMapValueKey);                ArrayList<Student> czbkMapValueValue = czbkMapValue                        .get(czbkMapValueKey);                for (Student s : czbkMapValueValue) {                    System.out.println("\t\t" + s.getName() + "---"                            + s.getAge());                }            }        }    }}

B)案例
A:ArrayList集合存储自定义对象的排序

/* * Collections可以针对ArrayList存储基本包装类的元素排序,存储自定义对象可不可以排序呢? */public class CollectionsDemo {    public static void main(String[] args) {        // 创建集合对象        List<Student> list = new ArrayList<Student>();        // 创建学生对象        Student s1 = new Student("林青霞", 27);        Student s2 = new Student("风清扬", 30);        Student s3 = new Student("刘晓曲", 28);        Student s4 = new Student("武鑫", 29);        Student s5 = new Student("林青霞", 27);        // 添加元素对象        list.add(s1);        list.add(s2);        list.add(s3);        list.add(s4);        list.add(s5);        // 排序        // 自然排序        // Collections.sort(list);        // 比较器排序        // 如果同时有自然排序和比较器排序,以比较器排序为主        Collections.sort(list, new Comparator<Student>() {            @Override            public int compare(Student s1, Student s2) {                int num = s2.getAge() - s1.getAge();                int num2 = num == 0 ? s1.getName().compareTo(s2.getName())                        : num;                return num2;            }        });        // 遍历集合        for (Student s : list) {            System.out.println(s.getName() + "---" + s.getAge());        }    }}
    B:模拟斗地主洗牌和发牌
* * 模拟斗地主洗牌和发牌 *  * 分析: *      A:创建一个牌盒 *      B:装牌 *      C:洗牌 *      D:发牌 *      E:看牌 */public class PokerDemo {    public static void main(String[] args) {        // 创建一个牌盒        ArrayList<String> array = new ArrayList<String>();        // 装牌        // 黑桃A,黑桃2,黑桃3,...黑桃K        // 红桃A,...        // 梅花A,...        // 方块A,...        // 定义一个花色数组        String[] colors = { "♠", "♥", "♣", "♦" };        // 定义一个点数数组        String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10",                "J", "Q", "K" };        // 装牌        for (String color : colors) {            for (String number : numbers) {                array.add(color.concat(number));            }        }        array.add("小王");        array.add("大王");        // 洗牌        Collections.shuffle(array);        // System.out.println("array:" + array);        // 发牌        ArrayList<String> fengQingYang = new ArrayList<String>();        ArrayList<String> linQingXia = new ArrayList<String>();        ArrayList<String> liuYi = new ArrayList<String>();        ArrayList<String> diPai = new ArrayList<String>();        for (int x = 0; x < array.size(); x++) {            if (x >= array.size() - 3) {                diPai.add(array.get(x));            } else if (x % 3 == 0) {                fengQingYang.add(array.get(x));            } else if (x % 3 == 1) {                linQingXia.add(array.get(x));            } else if (x % 3 == 2) {                liuYi.add(array.get(x));            }        }        // 看牌        lookPoker("风清扬", fengQingYang);        lookPoker("林青霞", linQingXia);        lookPoker("刘意", liuYi);        lookPoker("底牌", diPai);    }    public static void lookPoker(String name, ArrayList<String> array) {        System.out.print(name + "的牌是:");        for (String s : array) {            System.out.print(s + " ");        }        System.out.println();    }}
    C:模拟斗地主洗牌和发牌并对牌进行排序
/* * 思路: *      A:创建一个HashMap集合 *      B:创建一个ArrayList集合 *      C:创建花色数组和点数数组 *      D:从0开始往HashMap里面存储编号,并存储对应的牌 *        同时往ArrayList里面存储编号即可。 *      E:洗牌(洗的是编号) *      F:发牌(发的也是编号,为了保证编号是排序的,就创建TreeSet集合接收) *      G:看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌) */public class PokerDemo {    public static void main(String[] args) {        // 创建一个HashMap集合        HashMap<Integer, String> hm = new HashMap<Integer, String>();        // 创建一个ArrayList集合        ArrayList<Integer> array = new ArrayList<Integer>();        // 创建花色数组和点数数组        // 定义一个花色数组        String[] colors = { "♠", "♥", "♣", "♦" };        // 定义一个点数数组        String[] numbers = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q",                "K", "A", "2", };        // 从0开始往HashMap里面存储编号,并存储对应的牌,同时往ArrayList里面存储编号即可。        int index = 0;        for (String number : numbers) {            for (String color : colors) {                String poker = color.concat(number);                hm.put(index, poker);                array.add(index);                index++;            }        }        hm.put(index, "小王");        array.add(index);        index++;        hm.put(index, "大王");        array.add(index);        // 洗牌(洗的是编号)        Collections.shuffle(array);        // 发牌(发的也是编号,为了保证编号是排序的,就创建TreeSet集合接收)        TreeSet<Integer> fengQingYang = new TreeSet<Integer>();        TreeSet<Integer> linQingXia = new TreeSet<Integer>();        TreeSet<Integer> liuYi = new TreeSet<Integer>();        TreeSet<Integer> diPai = new TreeSet<Integer>();        for (int x = 0; x < array.size(); x++) {            if (x >= array.size() - 3) {                diPai.add(array.get(x));            } else if (x % 3 == 0) {                fengQingYang.add(array.get(x));            } else if (x % 3 == 1) {                linQingXia.add(array.get(x));            } else if (x % 3 == 2) {                liuYi.add(array.get(x));            }        }        // 看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌)        lookPoker("风清扬", fengQingYang, hm);        lookPoker("林青霞", linQingXia, hm);        lookPoker("刘意", liuYi, hm);        lookPoker("底牌", diPai, hm);    }    // 写看牌的功能    public static void lookPoker(String name, TreeSet<Integer> ts,            HashMap<Integer, String> hm) {        System.out.print(name + "的牌是:");        for (Integer key : ts) {            String value = hm.get(key);            System.out.print(value + " ");        }        System.out.println();    }}
0 0
原创粉丝点击