List与数组之间的相互转换

谁借莪1个温暖的怀抱¢ 2023-10-07 21:08 145阅读 0赞

文章目录

    • 一、前言
    • 二、List列表与对象数组
      • (一)对象List转对象数组
        • 1、toArray()方法
        • 2、Stream流的toArray()方法
        • 3、for循环
      • (二)、对象数组转对象List
        • 1、使用Arrays.asList()
        • 2、使用Collections.addAll()
        • 3、使用Stream中的Collector
        • 4、for循环
    • 三、List列表与基本数据类型数组
      • (一)、对象List转基本数据类型数组
      • 1、Stream流执行转换
        • 2、for循环
      • (二)、基本数据类型数组转对象List
        • 1、Stream流转换
        • 2、for循环

一、前言

  在Java编码中,我们经常会遇到List与数组的转换,包括对象List与对象数组的转换,以及对象List与基本数据类型数组的转换,下面详细介绍多种转换方式。

二、List列表与对象数组

  List列表中存储对象,如List<Integer>List<String>List<Person>,对象数组中同样存储相应的对象,如Integer[]、String[]、Person[],对象数组与对象List的转换可通过如下方式实现:

(一)对象List转对象数组

1、toArray()方法

  直接调用对象List的toArray()方法转换为对象数组,该方法的参数是T[],因此需要传入对应的对象数组构造函数,指定数组的长度,如下所示:

  1. ArrayList<Integer> integersList = new ArrayList<>(Arrays.asList(1,2,3));
  2. // 1、toArray()方法
  3. Integer[] integersArrau = integersList.toArray(new Integer[integersList.size()]);
2、Stream流的toArray()方法

  通过Stream流的toArray()方法,传入参数是对应对象的构造方法的方法引用,使用方式如下所示:

  1. ArrayList<Integer> integersList = new ArrayList<>(Arrays.asList(1,2,3));
  2. // 2、Stream流的toArray()方法
  3. Integer[] integersArray2 = integersList.stream().toArray(Integer[]::new);

  这个toArray()方法是Stream类下的,该方法说明如下所示:

  1. /**
  2. * Returns an array containing the elements of this stream, using the
  3. * provided {@code generator} function to allocate the returned array, as
  4. * well as any additional arrays that might be required for a partitioned
  5. * execution or for resizing.
  6. *
  7. * <p>This is a <a href="package-summary.html#StreamOps">terminal
  8. * operation</a>.
  9. *
  10. * @apiNote
  11. * The generator function takes an integer, which is the size of the
  12. * desired array, and produces an array of the desired size. This can be
  13. * concisely expressed with an array constructor reference:
  14. * <pre>{@code
  15. * Person[] men = people.stream()
  16. * .filter(p -> p.getGender() == MALE)
  17. * .toArray(Person[]::new);
  18. * }</pre>
  19. *
  20. * @param <A> the element type of the resulting array
  21. * @param generator a function which produces a new array of the desired
  22. * type and the provided length
  23. * @return an array containing the elements in this stream
  24. * @throws ArrayStoreException if the runtime type of the array returned
  25. * from the array generator is not a supertype of the runtime type of every
  26. * element in this stream
  27. */
  28. <A> A[] toArray(IntFunction<A[]> generator);

  该方法传入一个函数式接口,该接口对应一个方法引用,作用是创建一个新的指定类型和长度的数组,因此我们传入的参数就是一个Integer[]数组的构造方法的方法引用,最终得到的也就是一个Integer[]数组。

3、for循环

  过于简单,不再赘述。

(二)、对象数组转对象List

1、使用Arrays.asList()

  该方法通过传入一个对象数组,最后转换为一个对象List,如下所示:

  1. Integer[] integersArray = {
  2. 1, 2, 3};
  3. // 1、使用Arrays.asList()
  4. List<Integer> integersList = Arrays.asList(integersArray);

  asList方法传入的参数是一个可变参数,因此既可以传入多个参数,也可以传入一个数组,如下所示:

  1. /**
  2. * Returns a fixed-size list backed by the specified array. (Changes to
  3. * the returned list "write through" to the array.) This method acts
  4. * as bridge between array-based and collection-based APIs, in
  5. * combination with {@link Collection#toArray}. The returned list is
  6. * serializable and implements {@link RandomAccess}.
  7. *
  8. * <p>This method also provides a convenient way to create a fixed-size
  9. * list initialized to contain several elements:
  10. * <pre>
  11. * List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
  12. * </pre>
  13. *
  14. * @param <T> the class of the objects in the array
  15. * @param a the array by which the list will be backed
  16. * @return a list view of the specified array
  17. */
  18. @SafeVarargs
  19. @SuppressWarnings("varargs")
  20. public static <T> List<T> asList(T... a) {
  21. return new ArrayList<>(a);
  22. }
2、使用Collections.addAll()

  通过Collections集合类的static方法将一个对象数组转换为对象List,注意首先要创建出一个对象List,使用方式如下所示:

  1. Integer[] integersArray = {
  2. 1, 2, 3};
  3. // 2、使用Collections.addAll()
  4. ArrayList<Integer> integersList2 = new ArrayList<>();
  5. Collections.addAll(integersList2,integersArray);
3、使用Stream中的Collector

  JDK8之后可以使用Stream流来执行转换操作,通过Stream流的终结操作collect来指定将要转换得到的List:

  1. Integer[] integersArray = {
  2. 1, 2, 3};
  3. // 3、使用Stream中的Collector
  4. List<Integer> integersList3 = Arrays.stream(integersArray).collect(Collectors.toList());
4、for循环

  过于简单,不再赘述。

三、List列表与基本数据类型数组

  上面我们介绍了对象List列表与对象数组之间的转换,但是有些情况需要直接将对象List转换为基本数据类型数组,如List<Integer>int[]这种情况,下面详细介绍。

(一)、对象List转基本数据类型数组

1、Stream流执行转换

  通过Stream流执行转换,如List<Integer>转换为int[],通过Stream流的mapToInt()可将每个Integer转换为int,再输出为int数组,如下所示:

  1. ArrayList<Integer> integersList = new ArrayList<>(Arrays.asList(1,2,3));
  2. // 1、Stream流执行转换
  3. // 方法引用
  4. int[] arrays1 = integersList.stream().mapToInt(Integer::intValue).toArray();
  5. // lambda表达式
  6. int[] arrays2 = integersList.stream().mapToInt(i -> i).toArray();
2、for循环

  过于简单,不再赘述。

(二)、基本数据类型数组转对象List

1、Stream流转换

  以int[]数组来举例,通过Stream流的mapToObj()方法先将int[]数组中每个int值转换为Integer包装类,再通过collect执行终结操作转换为Integer的List。

  1. int[] integersArray = {
  2. 1, 2, 3};
  3. // 1、Stream流转换
  4. List<Integer> integersList = Arrays.stream(integersArray).mapToObj(Integer::new).collect(Collectors.toList());
2、for循环

  for循环是最简单、好用的方式,不再赘述。

发表评论

表情:
评论列表 (有 0 条评论,145人围观)

还没有评论,来说两句吧...

相关阅读