List与数组之间的相互转换

一、前言

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


二、List列表与对象数组

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


(一)对象List转对象数组

1、toArray()方法

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

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

2、Stream流的toArray()方法

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

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

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

/**
 * Returns an array containing the elements of this stream, using the
 * provided {@code generator} function to allocate the returned array, as
 * well as any additional arrays that might be required for a partitioned
 * execution or for resizing.
 *
 * <p>This is a <a href="package-summary.html#StreamOps">terminal
 * operation</a>.
 *
 * @apiNote
 * The generator function takes an integer, which is the size of the
 * desired array, and produces an array of the desired size.  This can be
 * concisely expressed with an array constructor reference:
 * <pre>{@code
 *     Person[] men = people.stream()
 *                          .filter(p -> p.getGender() == MALE)
 *                          .toArray(Person[]::new);
 * }</pre>
 *
 * @param <A> the element type of the resulting array
 * @param generator a function which produces a new array of the desired
 *                  type and the provided length
 * @return an array containing the elements in this stream
 * @throws ArrayStoreException if the runtime type of the array returned
 * from the array generator is not a supertype of the runtime type of every
 * element in this stream
 */
<A> A[] toArray(IntFunction<A[]> generator);

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


3、for循环

  过于简单,不再赘述。


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

1、使用Arrays.asList()

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

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

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

/**
 * Returns a fixed-size list backed by the specified array.  (Changes to
 * the returned list "write through" to the array.)  This method acts
 * as bridge between array-based and collection-based APIs, in
 * combination with {@link Collection#toArray}.  The returned list is
 * serializable and implements {@link RandomAccess}.
 *
 * <p>This method also provides a convenient way to create a fixed-size
 * list initialized to contain several elements:
 * <pre>
 *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
 * </pre>
 *
 * @param <T> the class of the objects in the array
 * @param a the array by which the list will be backed
 * @return a list view of the specified array
 */
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}

2、使用Collections.addAll()

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

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

3、使用Stream中的Collector

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

Integer[] integersArray = {1, 2, 3};
// 3、使用Stream中的Collector
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数组,如下所示:

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

2、for循环

  过于简单,不再赘述。


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

1、Stream流转换

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

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

2、for循环

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

  • 22
    点赞
  • 79
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 将List转换数组的最简单方法是使用List的toArray()方法。例如: ```java List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("orange"); String[] arr = list.toArray(new String[list.size()]); // 输出数组元素 for (String fruit : arr) { System.out.println(fruit); } ``` 在上面的示例中,我们首先创建了一个包含三个水果的List。然后,我们使用toArray()方法将List转换为String数组。请注意,我们需要传递一个新的String数组作为参数,该数组的大小等于List的大小。最后,我们使用 for-each 循环遍历数组并输出每个元素。 ### 回答2: Java中,将List转换数组有两种常用的方法: 方法一:使用toArray()方法 List提供了一个toArray()方法,该方法可以将List对象转换成一个数组。代码示例如下: List<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); String[] array = list.toArray(new String[0]); 使用toArray()方法时,如果参数传入一个长度为0的数组,那么该方法会根据List的大小,动态创建一个与List大小相同的新数组,并将List中的元素复制到新数组中。 方法二:使用Stream API Stream API是Java 8引入的一个强大的功能,它可以简化集合的操作。通过Stream API,我们可以将List转换成一个数组List<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); String[] array = list.stream().toArray(String[]::new); 在上述代码中,我们使用stream()方法将List转换成Stream对象,然后使用toArray()方法将Stream转换数组。需要注意的是,toArray()方法的参数是一个数组的构造器引用,这样toArray()方法会根据List的大小,动态创建一个与List大小相同的新数组。 通过上述两种方法,我们可以将List对象转换数组,方便进行数组相关的操作。 ### 回答3: Java中,可以通过list的toArray方法将一个List转换数组。 例如,假设有一个List<Integer>,可以使用以下代码将其转换数组: ```java List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); Integer[] array = list.toArray(new Integer[list.size()]); ``` 上述代码中,list.toArray方法接受一个数组作为参数,可以通过这个参数指定生成的数组的类型和长度。在这个例子中,我们将list的长度作为数组的长度,并通过Integer[]指定生成的数组类型为Integer数组。 需要注意的是,由于泛型的擦除特性,List转换数组时不能直接使用int[]或其他基本数据类型的数组,而需要使用对应的包装类型,比如Integer[]。 另外,在JDK 1.5及以上版本,还提供了一个无参的toArray方法,可以根据List中的元素类型自动创建合适长度的数组。例如: ```java List<String> list = new ArrayList<>(); list.add("Hello"); list.add("World"); String[] array = list.toArray(new String[0]); ``` 在这个例子中,通过传递一个长度为0的String数组List会根据元素的类型自动创建合适长度的数组。这样做可以简化代码,但在性能方面可能会有些损失。 综上所述,list数组可以通过list的toArray方法实现,需要注意参数的类型和长度的选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值