集合中常用方法的使用

集合中常用方法的使用

数组和List之间的转化

数组转化为List

        // 1.数组转化为List
        Integer a[] = {1, 3, 4, 5, 2};
        List<Integer> lista = new ArrayList<>();
        // 1.1 通过addAll()方法来转换
        Collections.addAll(lista, a);
        lista.forEach(System.out::println);
        // 1.2 通过asList()方法来转换,这里所获取到的List只能读取(类似于视图),不能进行增删改的操作
        List<Integer> lista2 = Arrays.asList(a);
        lista2.forEach(System.out::println);
        // 通过再次转化后的List可以进行增删改操作
        List<Integer> lista2l = new ArrayList<>(Arrays.asList(a));
        lista2l.forEach(System.out::println);
        // 1.3 采用API9的静态方法
        List<Integer> lista3 = List.of(a);
        lista3.forEach(System.out::println);
        // 1.4 函数式Stream写法
        int[] cardNumberArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        List<Integer> collect1 = Arrays.stream(cardNumberArray).boxed().collect(Collectors.toList());
        collect1.forEach(System.out::println);

List转化为数组

 		// 2.List转化为数组
        List<Integer> listb = Arrays.asList(1, 3, 2, 5, 4);
        // 2.1 采用toArray()方法来转换
        // 转化为任意类型的数组
        Object[] objects = listb.toArray();
        System.out.println(Arrays.toString(objects));
        // 转化为固定数据类型的数组
        Integer[] b = listb.toArray(new Integer[listb.size()]);
        System.out.println(Arrays.toString(b));
        // 采用函数式接口的写法(简洁写法)
        Integer[] b2 = listb.toArray(Integer[]::new);
        System.out.println(Arrays.toString(b2));

        // 2.2 采用stream的流式写法
        // 把int的List转化成int的数组
        List<Integer> listc = Arrays.asList(1, 4, 2, 3, 5, 6);
        int[] arrc = listc.stream().mapToInt(Integer::intValue).toArray();
        System.out.println(Arrays.toString(arrc));

        // 把String的List转换成int的数组
        List<String> listd = Arrays.asList("1", "4", "2", "3", "5");
        int[] arr = listd.stream().flatMapToInt(num -> IntStream.of(Integer.parseInt(num))).toArray();
        listd.stream().flatMapToInt(num -> IntStream.of(Integer.parseInt(num))).forEach(System.out::println);
        System.out.println(Arrays.toString(arr));

        // 2.3 使用collections工具类的copy()方法
        List<Integer> list = Arrays.asList(new Integer[listb.size()]);
        Collections.copy(list, listb);
        list.forEach(System.out::println);

包装类型的数据转化

list->array(注:只能转化到包装类)

        List<Integer> list = Arrays.asList(1, 3, 4, 5, 2);
        Integer[] array = list.toArray(Integer[]::new);
        System.out.println(Arrays.toString(array));

array->list(注:只能用包装类转化)

 		Integer[] array = {1, 3, 5, 4, 2};
        List<Integer> list = Arrays.asList(array);
        list.forEach(System.out::println);
        System.out.println(list);

数组基本类型和包装类之间转化

包装类转为基本类型

        Integer[] basicArr = {1, 3, 5, 4, 2};
        int[] ints = Arrays.stream(basicArr).mapToInt(Integer::intValue).toArray();
        System.out.println(Arrays.toString(ints));

基本类型转为包装类

        int [] array = {1, 3, 5, 4, 2};
        Integer [] ints = Arrays.stream(array).boxed().toArray(Integer[]::new);
        System.out.println(Arrays.toString(ints));

数组和List的排序

数组排序

  1. 升序
        Integer a[] = {1, 4, 3, 2, 6, 5};
        Arrays.sort(a);
        System.out.println(Arrays.toString(a));

结果:

[1, 2, 3, 4, 5, 6] 
  1. 降序
 		Integer a[] = {1, 4, 3, 2, 6, 5};
        Arrays.sort(a, Comparator.reverseOrder());
        System.out.println(Arrays.toString(a));

结果:

[6, 5, 4, 3, 2, 1]

List排序

升序和降序

        List<Integer> list = Arrays.asList(1, 4, 3, 2, 6, 5);
        Collections.sort(list, Comparator.reverseOrder());
        System.out.println(list);

结果:

[6, 5, 4, 3, 2, 1]

Comparator和Comparable接口

  • Comparable: 自己和自己比较,属于自营性质的比较器。以-able结尾,表示自身具备某种能力,比较方法为compareTo
  • Comparator: 第三方比较器。以-or结尾,表示自身是比较器的实践者,比较方法为compare

如果这个排序规则不符合业务方需求,那么直接修改compareTo方法不是一定可行的。有以下原因:

  1. 根据开闭原则,最好不要对自己已经交付的类进行修改。
  2. 这个排序规则有可能被有其他业务方在使用。
  3. 这个Person类是他人提供的类,我们没有源码。

这时候就需要用到Comparator比较器了,Comparator比较器可以让业务方根据自身需求修改排序规则。

Comparable

Comparable属于内部比较器,需要重写compareTo()方法

案例1:请声明一个员工类Employee,有编号,姓名,薪资,实现java.lang.Comparable接口,按照编号升序排序。
在测试类TestEmployee中,创建员工数组,并初始化5个员工,
(1)调用Arrays.sort(Object[] arr)排序,按照编号升序排列
(2)调用Arrays.sort(Object[] arr,Comparator c)排序,按照薪资降序排列

public class Employee implements Comparable<Employee> {
    private int id;

    private String name;

    private int salary;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public Employee(int id, String name, int salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    @Override
    public int compareTo(Employee employee) {
        return id - employee.getId();
    }

    @Override
    public String toString() {
        return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", salary=" + salary + '}';
    }
}
public class EmployeeTest {
    public static void main(String[] args) {
        Employee employee = new Employee(1, "zs", 2);
        Employee employee2 = new Employee(2, "ls", 3);
        Employee employee3 = new Employee(3, "ww", 4);
        Employee employee4 = new Employee(4, "zl", 5);
        List<Employee> list = new ArrayList<>();
        list.add(employee);
        list.add(employee2);
        list.add(employee3);
        list.add(employee4);
        Collections.sort(list);
        list.forEach(System.out::println);
    }
}

结果:

Employee{id=1, name='zs', salary=2}
Employee{id=2, name='ls', salary=3}
Employee{id=3, name='ww', salary=4}
Employee{id=4, name='zl', salary=5}

Comparator

Comparator属于外部比较器,需要重写compare()方法

    public static void main(String[] args) {
        Employee employee = new Employee(1, "zs", 2000);
        Employee employee2 = new Employee(2, "ls", 5000);
        Employee employee3 = new Employee(3, "ww", 3000);
        Employee employee4 = new Employee(4, "zl", 4000);
        List<Employee> list = new ArrayList<>();
        list.add(employee);
        list.add(employee2);
        list.add(employee3);
        list.add(employee4);
        Collections.sort(list, (v1, v2) -> v2.getSalary()-v1.getSalary());
        list.forEach(System.out::println);
    }

结果:

Employee{id=2, name='ls', salary=5000}
Employee{id=4, name='zl', salary=4000}
Employee{id=3, name='ww', salary=3000}
Employee{id=1, name='zs', salary=2000}

HashMap的排序

https://www.cnblogs.com/yzhmj/p/14919027.html

案例:根据value进行降序排列,在value相同时,根据key进行升序排列

    public static void main(String[] args) {
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0, 28);
        map.put(2, 28);
        map.put(5, 50);
        ArrayList<Map.Entry<Integer, Integer>> entries = new ArrayList<>(map.entrySet());
        Collections.sort(entries, (e1, e2) -> {
            int re = e2.getValue() - e1.getValue();
            if (re == 0) {
                return e1.getKey() - e2.getKey();
            } else {
                return re;
            }
        });
        entries.forEach(k -> System.out.println(k));
        List<Integer> klist = entries.stream().map(Map.Entry::getKey).collect(Collectors.toList());
        System.out.println(klist);
    }

结果:

5=50
0=28
2=28
[5, 0, 2]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值