java Collections工具类的 一些功能(查找,最值,乱序,逆序,排序,交换,替换,让集合线程同步)

Collections Api : Collections


1.数组转集合
//数组转成集合List
        List list=new ArrayList();
        Integer[] arr={12,2,45,46,76,23,45,65};
        Collections.addAll(list,arr);

2.集合通过key查找其位置
        //集合进行查找其key的位置
        List list=new ArrayList();
        Integer[] arr={12,2,45,46,76,23,45,65};
        Collections.addAll(list,arr);
        System.out.println(list.toString());
        System.out.println("45数字位置(从0开始):"+Collections.binarySearch(list,45));
        System.out.println("0数字的位置(不存在):"+Collections.binarySearch(list,0));

3.集合找出最大值和最小值
        //集合进行查找其最大值和最小值
        List list=new ArrayList();
        Integer[] arr={12,2,45,46,76,23,45,65};
        Collections.addAll(list,arr);
        System.out.println(list.toString());
        System.out.println("最大值:"+Collections.max(list));
        System.out.println("最小值:"+Collections.min(list));
4.集合的复制
//集合拷贝 必须要 被拷贝的大于等于拷贝的大小 而且只是覆盖前面部分 并不是删除覆盖
        List list=new ArrayList();
        Integer[] arr={12,2,45,46,76,23,45,65};
        Collections.addAll(list,arr);
        List lists=new ArrayList();
        //如果下面一句删掉 是没法让lists大小 大于等于 list 会抛出异常
        Integer[] arr2={12,2,45,111,76,23,45,65,222};
        Collections.addAll(lists,arr2);
        try {
            Collections.copy(lists,list);
        }
        catch (Exception e)
        {
            //lists的大小-list集合的大小
            System.out.println(lists.size()-list.size());
        }
        System.out.println(lists.toString());
5.乱序
List list=new ArrayList();
        Integer[] arr={12,3423,5,5,66,7,8,43,32,4};
        Collections.addAll(list,arr);
        //乱序
        Collections.shuffle(list);
6.逆序
List list=new ArrayList();
        Integer[] arr={12,3423,5,5,66,7,8,43,32,4};
        Collections.addAll(list,arr);
        //逆序
        Collections.reverse(list);
7.排序
List list=new ArrayList();
        Integer[] arr={12,3423,5,5,66,7,8,43,32,4};
        Collections.addAll(list,arr);
        //排序从小到大
        Collections.sort(list);
        //排序从大到小
        Collections.sort(list,new Comparator() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });
8.交换
List list=new ArrayList();
        Integer[] arr={12,3423,5,-5,66,7,8,43,32,4};
        Collections.addAll(list,arr);
        //交换位置 (坐标从0开始)
        Collections.swap(list,2,3);
9.替换
        List list=new ArrayList();
        Integer[] arr={12,8,5,-5,8,7,8,43,32,4};
        Collections.addAll(list,arr);
        //替换
        Integer oldval=8;
        Integer newval=999;
        Collections.replaceAll(list,oldval,newval);
10.让线程同步
        Collection collections=Collections.synchronizedCollection(new ArrayList());
        List list=Collections.synchronizedList(new ArrayList<>());
        Set ser=Collections.synchronizedSet(new TreeSet<>());
        Map map=Collections.synchronizedMap(new TreeMap());













你可能感兴趣的:(我的日志,Java,集合)