zoukankan      html  css  js  c++  java
  • Collections集合工具类

    java.util.Collections

    静态方法:

    public static <T> boolean addAll(Collection<T> c, T...elements):往集合中添加一些元素
    public static void shuffle(List<?> list):打乱集合的顺序
    public static void sort(List<?> list):默认升序,只能传递List,不能传递、Set,如果对自定义类排序,必须实现接口Comparable,重写compareTo方法
    public ststic <T> void sort(List<T> list, Comparator<? super T>) : 将集合元素按照指定规则排序
    
    public class Demo01Collections {
    
        public static void main(String[] args) {
            ArrayList<String> list = new ArrayList<>();
            Collections.addAll(list, "a", "b", "c", "d");
            System.out.println(list);// [a, b, c, d]
    
            Collections.shuffle(list);// 打乱顺序
            System.out.println(list);// [b, c, d, a],每次调用都是随机打乱
        }
    }
    
    
    package cn.zhuobo.day10.aboutCollections;
    
    public class Person implements Comparable<Person>{
        private String name;
        private int age;
    
    //重写compareTo方法,自定义比较规则,现在是按照年龄升序排序
        @Override
        public int compareTo(Person o) {
            return this.getAge() - o.getAge();//自己-参数就是升序,反之就是降序
    }
    
    

    public ststic void sort(List list, Comparator<? super T>) : 将集合元素按照指定规则排序

    public class Demo01Collections {
    
        public static void main(String[] args) {
            ArrayList<Person> list = new ArrayList<>();
            list.add(new Person("aaa", 18));
            list.add(new Person("bbb", 16));
            list.add(new Person("ccc", 18));
            list.add(new Person("ddd", 15));
    
            System.out.println(list);
    
            Collections.sort(list);
            System.out.println(list);
    
            Collections.sort(list, new Comparator<Person>() {
                @Override
                public int compare(Person o1, Person o2) {
                    int result = o2.getAge() - o1.getAge();//第二个-第一个(按照年龄降序)
                    if(result == 0) result = o1.getName().charAt(0) - o2.getName().charAt(0);// 如果年龄相同,按照首字符升序
                    return result;
                }
    
            });
    
            System.out.println(list);
        }
    }
    
  • 相关阅读:
    spring的@Transactional注解详细用法
    解决:No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency
    SpringBoot2 启动报错 Failed to auto-configure a DataSource
    SpringBoot2 全局异常处理
    Intellij IDEA 将工程转换成maven工程 详解
    js性能优化
    JDK故障处理工具箱
    编写高性能的jquery代码
    maven工程解决jar包冲突依赖问题
    spring aop中xml配置文件中标签和属性对应的类
  • 原文地址:https://www.cnblogs.com/zhuobo/p/10629357.html
Copyright © 2011-2022 走看看