集合的工具类Collections

Collections

数组的工具Arrays,集合的工具类Collections

public static <T> boolean addAll(Collection<? super T> c, T... elements)
    //向指定集合里面添加元素:
private static void demo4() {
    List<Integer> list=new ArrayList<>(10);
    Collections.addAll(list,10,89,32,4,21,54,3,12,5);
    System.out.println(list);
}

当集合是线程不安全的时候可以用collections的方法来将线程变得安全:

List<User> list1=Collections.synchronizedList(new ArrayList<>(10));
//将线程不安全的集合,转换成线程安全

打乱集合中元素的顺序:

Collections.shuffle(list);//打乱集合中元素顺序

我需要对结果进行排序:

comparable

Collections.sort();
private static void demo4() {
    List<Integer> list=new ArrayList<>(10);
    Collections.addAll(list,10,89,32,4,21,54,3,12,5);
    Collections.sort(list);
    System.out.println(list);//[3, 4, 5, 10, 12, 21, 32, 54, 89]
}

前面也说过,是因为该类型实现了comparable,并且重写了里面的compare方法 ,但是换成是没有实现排序的类型呢?

@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User implements Comparable<User>  {
    private String name;
    private Integer id;
    private Integer age;

    @Override
    public int compareTo(User user) {
        return this.age.compareTo(user.age);
    }
}
private static void demo3() {
    List<User> list=new ArrayList<>(10);
   Collections.addAll(list,
           new User("tom",3627,21),
           new User("jack",3526,20),
           new User("jim",2540,23),
           new User("jerry",3552,15),
           new User("tom",9584,15)
           );
   //按照年龄升序排列
    Collections.sort(list);
    list.forEach(System.out::println);
}

如果年龄相等的话按照id来进行降序排列:

public class User implements Comparable<User>  {
    private String name;
    private Integer id;
    private Integer age;
    @Override
    public int compareTo(User user) {
        int i = this.age.compareTo(user.age);
        if(i==0){
           i= user.id.compareTo(this.id);
        }
        return i;
    }
}

上面用的是内部比较器,在类的内部实现接口,改变类的结构从而实现排序,那么下面我们用外部比较器的方式来进行比较

comparator

使用list自带的sort来进行排序:

private static void demo3() {
    List<User> list=new ArrayList<>(10);
   Collections.addAll(list,
           new User("tom",3627,21),
           new User("jack",3526,20),
           new User("jim",2540,23),
           new User("jerry",3552,15),
           new User("tom",9884,15)
           );
   list.sort((user1,user2)-> {
       int i= (user1.getAge().compareTo(user2.getAge()));
        if(i==0){
            i=user2.getId().compareTo(user1.getId());
        }
           return i;

   });
    list.forEach(System.out::println);
}

也可以直接调用comparator里面的静态方法:

语法:

集合.sort(Comparator.comparing(泛型对象::想要排序的元素));

list.sort(Comparator.comparing(User::getAge));
list.forEach(System.out::println);

如果后面还想继续根据id排序,可以用thenCompararing()

list.sort(Comparator.comparing(User::getAge).thenComparing(User::getId));
list.forEach(System.out::println);
posted @ 2022-11-23 13:12  Liku007  阅读(22)  评论(0编辑  收藏  举报