集合的有关例题

集合测试

Collection

Test_1 ScannerTest

使用Scanner从键盘读取一行输入,去掉重复字符, 打印出不同字符

/***
 * 使用Scanner从键盘读取一行输入,去掉其中重复字符, 打印出不同的那些字符
 */
public class ScannerTest {

    public static void main(String[] args) {
        //有序:HashSet<Character> hs = new LinkedHashSet<>();
        HashSet<Character> hs = new HashSet<>();
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();//接受获得的字符串
        char[] arr = line.toCharArray();//字符串转换成字符数组
        //把接收到的字符串遍历添加到集合
        for (char c : arr) {
            hs.add(c);
        }
        //遍历HashSet集合
        for (Character h : hs) {
            System.out.print(h + "	");
        }
        System.out.println();

    }

}

输出结果: 
aadddccccbbbbbggf
a	b	c	d	f	g  

Test_2 ArrayListTest

需求: 将ArrayList集合中的重复元素去掉

/**
 * 需求: 将ArrayList集合中的重复元素去掉
 */
public class ArrayListTest {

    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("aaa");
        list.add("abc");
        list.add("bbc");
        list.add("bbc");
        list.add("bbc");
        list.add("world");
        list.add("world");
        list.add("hello");
        for (String s : list) {
            System.out.print(s + "	");
        }
        System.out.println();

        getList(list);

    }

    private static void getList(ArrayList<String> list) {

        HashSet<String> hs = new LinkedHashSet<>();//无序: HashSet<>()
        hs.addAll(list);
        //for (String s : list) {
        //    hs.add(s);
        //}
        list.clear();
        list.addAll(hs);
        System.out.println(list);
    }

}

输出结果:
aaa	aaa	abc	bbc	bbc	bbc	world	world	hello	
[aaa, abc, bbc, world, hello]

Test_3 RandomTest1

需求:编写一个程序,获取10个1至20的随机数,要求随机数不能重复。并把最终的随机数输出到控制台。

/**
 * 需求:编写一个程序,获取10个1至20的随机数,要求随机数不能重复。
 * 并把最终的随机数输出到控制台。
 */
public class RandomTest {

    public static void main(String[] args) {

        HashSet<Integer> hs = new HashSet<>();
        Random random = new Random();
        int count = 0;
        while (hs.size() < 10) {
            //获取随机数
            int num = random.nextInt(20) + 1;//随机数上限 : 20
            count++;
            hs.add(num);
        }
        System.out.println("一共获得了" + count + "随机数");
        for (Integer i : hs) {
            System.out.print(i + "	");
        }
        System.out.println();
    }

}

输出结果:
一共获得了12随机数
16	17	1	2	19	6	9	12	13	15

Test_4 RandomTest2

用一个大集合存入20个随机数字,然后筛选其中的偶数元素,放到小集合当中然后进行遍历输出

/**
 * 用一个大集合存入20个随机数字,然后筛选其中的偶数元素,放到小集合当中然后进行遍历输出
 */
public class RandomList {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        List<Integer> list1 = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            list.add((int) (Math.random()*100));
        }
        for (Integer i : list) {
            System.out.print(i + " ");
        }
        System.out.println();
        for (Integer i : list) {
            if (i % 2 == 0) {
                list1.add(i);
            }
        }

        for (Integer i : list1) {
            System.out.print(i + " ");
        }
        System.out.println();
    }

}

输出结果:
12 34 85 14 28 58 16 45 40 27 74 88 58 58 41 39 0 3 80 10 
12 34 14 28 58 16 40 74 88 58 58 0 80 10 

Test_5 ReceiveTest

程序启动后, 可以从键盘输入接收多个整数,直到输入quit时结束输入. 把所有输入的整数倒序排列打印

/***
 * 程序启动后, 可以从键盘输入接收多个整数,
 * 直到输入quit时结束输入. 把所有输入的整数倒序排列打印
 */
public class TreeSetTest {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        TreeSet<Integer> ts = new TreeSet<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                int num = o2 - o1;//倒叙排列二叉树. 默认正序排列为从小到大
                return num == 0 ? 1 : num;
            }
        });
        while (true) {
            String str = sc.nextLine();
            if ("quit".equals(str)) break;
            try {
                int num = Integer.parseInt(str);//将数字字符串转换成数字
                ts.add(num);
            } catch (Exception e) {
                System.out.println("error");
            }
        }

        for (Integer t : ts) {
            System.out.println(t);
        }

    }

}

输出结果: 
12
123
222
1
quit
    
222
123
12
1

Test_6 AddListTest

需求:有一个集合,我想判断里面有没有"world"这个元素,如果有,就添加一个"javaee"元素,请写代码实现

/***
 * 需求:我有一个集合,请问,我想判断里面有没有"world"这个元素
 * 如果有,我就添加一个"javaee"元素,请写代码实现
 */
public class ListTest {

    public static void main(String[] args) {

        List list = new ArrayList();
        list.add("a");
        list.add("b");
        list.add("world");
        list.add("d");
        list.add("e");
        // == 判断是否指向同一个内存空间
        // .equals 判断所指向的内存空间的值是否相同

        //使用iterator 一边通过迭代器遍历list, 一边修改list,会出现并发异常
        //Iterator it = list.iterator();
        ListIterator it = list.listIterator();
        while (it.hasNext()) {
            String str = (String) it.next();
            if ("world".equals(str)) {
                it.add("javaee");
                //list.add("javaee");
            }
        }
        System.out.println(list);

        /*
        for (int i = 0; i < list.size(); i++) {
            //Object --> String
            String str = (String) list.get(i);
            if ("world".equals(str)) {
                list.add("javaee");
            }
        }
        System.out.println(list);*/

        /*
        boolean f = list.contains("world");
        if ("true".equals(f)) {
            list.add("javaee");
        }
        System.out.println(list);*/

    }

}

输出结果:
[a, b, world, javaee, d, e]

Test_7 SortTest

1-10个数字

奇数在后偶数在前

偶数降序,奇数升序

/**
 * 1-10个数字
 * 奇数在后偶数在前
 * 偶数降序,奇数升序
 */
public class TreeSetSort2 {

    public static void main(String[] args) {

        Set<Integer> set = new TreeSet<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                if (o1 % 2 == 0) {
                    if (o2 % 2 == 0) {
                        return o2 - o1;
                    }else {
                        return -1;
                    }
                }else {
                    if (o2 % 2 != 0) {
                        return o1 - o2;
                    }else {
                        return 1;
                    }
                }
            }
        });
        for (int i = 1; i <= 10; i++) {
            set.add(i);
        }
        System.out.println(set);
    }

}

输出结果:
[10, 8, 6, 4, 2, 1, 3, 5, 7, 9]

Map

Test_1 CountTest1

需求:统计字符串中每个字符出现的次数 HashMap实现

/***
 * 需求:统计字符串中每个字符出现的次数 HashMap实现
 */
public class CountTest {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        char[] arr = str.toCharArray(); //将输入的字符串转化成字符数组
        HashMap<Character, Integer> map = new HashMap<>();
        for (char c : arr) {
            if (map.containsKey(c)) {
                map.put(c, map.get(c) + 1);
            }else {
                map.put(c, 1);
            }

        }

        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }


    }

}

输出结果:
aabbccddd123321
    
a : 2
1 : 2
b : 2
2 : 2
c : 2
3 : 2
d : 3
    
/**
 * 统计每个字符串出现的次数 TrreeMap实现
 * String s = "aabbddccaefdd";
 */
public class TreeMapCount {

    public static void main(String[] args) {

        Map<Character, Integer> map = new TreeMap<>();
        String s = "aabbddccaefdd";
        char[] array = s.toCharArray();
        for (char c : array) {
            if (!map.containsKey(c)) {
                map.put(c, 1);
            }else {
                map.put(c, map.get(c) + 1);
            }
        }
        for (Character c : map.keySet()) {
            System.out.println(c + " : " + map.get(c));
        }
    }

}  

输出结果:
a : 3
b : 2
c : 2
d : 4
e : 1
f : 1

Test_2 CountTest2

在控制台输入一句英文:The hard part is not making the decision but it is living with it

  • 每个单词之间用空白隔开。
  • 使用HashMap统计该句英文中每个单词出现的次数
/***
 * 在控制台输入一句英文:The hard part is not making the decision but it is living with it
 *    每个单词之间用空白隔开。
 *    使用HashMap统计该句英文中每个单词出现的次数
 */
public class TestWork1 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        //把输入的字符串统一转成小写单词处理
        String line = sc.nextLine().toLowerCase();
        String[] arr = line.split(" ");

        Map<String, Integer> map = new HashMap();
        for (String s : arr) {
            if (!map.containsKey(s)) {
                map.put(s, 1);
            }else {
                map.put(s, map.get(s) + 1);
            }
        }
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }

}

输出结果:
The hard part is not making the decision but it is living with it
    
the: 2
but: 1
with: 1
not: 1
making: 1
living: 1
decision: 1
part: 1
is: 2
hard: 1
it: 2

Test_3 DouDiZhu

斗地主

/**
 * 斗地主
 */
public class DouDiZhu {

    public static void main(String[] args) {

        String[] color = {"♠", "♥", "♣", "♦"};
        String[] number = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
        Map<Integer, String> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();

        //把颜色和数字组合放进map集合中
        int index = 0;
        for (String s : color) {
            for (String s1 : number) {
                map.put(index, s.concat(s1));
                list.add(index);
                index++;
            }
        }
        //index++;
        //存大小王
        map.put(index, "小王");
        list.add(index);
        index++;
        map.put(index, "大王");
        list.add(index);
        //System.out.println(map);
        System.out.println(map.size());

        //洗牌
        Collections.shuffle(list);
        //System.out.println(list);

        //发牌 将list集合随机排列后放进三个玩家集合和一个底牌集合中 TreeSet在输出时会自动按照自然数排序	【中序遍历】
        TreeSet<Integer> play1 = new TreeSet<>();
        TreeSet<Integer> play2 = new TreeSet<>();
        TreeSet<Integer> play3 = new TreeSet<>();
        TreeSet<Integer> UnderCard = new TreeSet<>();

        /*for (Integer i : list) {
            System.out.print(i + " ");
        }
        System.out.println();*/
        for (int i = 0; i < list.size(); i++) {
            if (i >= list.size()-3) {
                UnderCard.add(list.get(i));
            }else if (i % 3 == 0) {
                play1.add(list.get(i));
            }else if (i % 3 == 1) {
                play2.add(list.get(i));
            }else
                play3.add(list.get(i));
        }

        //玩家看牌
        LookPoker(play1, map, "player1");
        LookPoker(play2, map, "player2");
        LookPoker(play3, map, "player3");
        LookPoker(UnderCard, map, "UnderCard");


    }

    private static void LookPoker(TreeSet<Integer> player, Map<Integer, String> map, String playerName) {
        System.out.print(playerName + ": ");
        for (Integer i : player) {
            System.out.print(map.get(i) + "	");
        }
        System.out.println();
    }

}

输出结果[随机性]:
54
♠3	♣3	♠4	♠6	♣6	♠7	♦7	♥8	♦8	♥9	♣10	♥J	♦Q	♣A	♥2	♦2	大王	
♥3	♠5	♥5	♦5	♥6	♦6	♥7	♠8	♦10	♠J	♣J	♠Q	♣Q	♠K	♥K	♠A	♦A	
♦3	♣4	♦4	♣5	♣7	♣8	♦9	♠10	♥10	♦J	♥Q	♣K	♦K	♥A	♠2	♣2	小王	
♥4	♠9	♣9
原文地址:https://www.cnblogs.com/xly1029/p/13879373.html