在java中把数组转换为列表的5种方法

157 阅读2分钟

在这篇文章中,我们将学习在java中把数组转换为数组列表的多种方法。

数组是静态的和固定大小的数据结构。ArrayList是动态数据结构。

将数组转换为数组列表

例如,让我们创建一个字符串数组,如下图所示。

String[] words = new String[] { "one","two","three" };
(or)
String words[] = { "one","two","three" };

创建一个字符串数组,并将其初始化为字符串列表。

现在,我们将看到将其转换为列表实现的多种方法

使用普通的for循环

这个方法是直接使用for循环的。

  • 使用for循环从一个数组中遍历每个字符串
  • 使用add 方法将其添加到数组中

下面是一个例子

 List list = new ArrayList<>();
        for (String word : words) {
            list.add(word);
        }

Collections.addAll方法

Collections是java类,每个列表的实现都可以扩展它。

addAll方法接受列表和数组并返回布尔值。

  • 我们已经有了上面声明的字符串数组
  • 首先创建一个目标空列表
  • 将列表和数组传给addAll()方法。
  • 数组被转换为列表
  • list参数保存数组的值
List list = new ArrayList<>();
Collections.addAll(list,words);

与其他asListfor循环迭代相比,这个方法运行得更快。

java 7 java.util.Arrays方法asList

java.util.Arrays有多种方法来操作java中的数组。

asList 该方法将固定大小的数组转换为List集合的实现。

将数组传递给asList方法并返回一个java.util.List。

 List list = Arrays.asList(words);

使用java8流

在java8中引入的流可以很容易地操作迭代。你可以了解java8中的流图

  • Arrays.stream将数组作为一个参数,并且
  • 使用流对每个元素进行迭代和映射
  • 使用collect方法收集元素
  • 使用Collectors.toList()方法返回列表。
List list =Arrays.stream(words).collect(Collectors.toList());
System.out.println(list);

这对对象类型是有效的,但对原始类型则无效。

如何将原始数组转换为对象的数组列表?

比如说:

  • 我们有一个int数组,初始化为数字
  • 迭代并使用流方法映射每个元素。
  • 使用boxed()方法将每个原始元素装箱为对象。
  • 最后收集并返回List方法
int[] ints = new int[] {15,21,14,17,25};
List listNumbers =Arrays.stream(ints).boxed().collect(Collectors.toList());

让我们把数组转换成List、ArrayList和LinkedList。

下面的例子是一系列的步骤

  • 使用流媒体对数组进行遍历
  • 使用boxed()方法将原始数据转换为对象类型。
  • 使用Collectors.toList() 方法收集并返回List
  • 使用Collectors.toCollection(ArrayList::new) 方法收集并返回ArrayList
  • 使用Collectors.toCollection(LinkedList::new) 方法收集并返回LinkedList
List listNumbers =Arrays.stream(ints).boxed().collect(Collectors.toList());

ArrayList arrayLists =Arrays.stream(ints).boxed().collect(Collectors.toCollection(ArrayList::new));

LinkedList linkedLists =Arrays.stream(ints).boxed().collect(Collectors.toCollection(LinkedList::new));

java9使用List.of方法

List在java9中增加了重载的of()方法。你可以查看java9的特点

List.of()是一个静态的工厂方法,它返回有数组元素的可免疫列表

List immutablewordList = List.of(words);

如果你想返回可变的列表,你可以使用以下方法

ArrayList mutablewordList = new ArrayList<>(List.of(words));

使用guava库的Lists.newArrayList方法

guava是google为java开发的核心库,它比java集合有很多新的功能。

对于maven项目,你必须添加以下依赖性


    com.google.guava
    guava
    30.1.1-jre

com.google.common.collect.Lists有一个方法newArrayList ,它接收数组并返回数组列表。

下面是一个例子

import java.util.*;
import com.google.common.collect.Lists;

public class Main {
    public static void main(String[] args) {
        String[] words = new String[]{"one", "two", "three"};
        List list = Lists.newArrayList(words);
    }
}