如何在Java中将数组转换为列表?

我使用了Arrays.asList(),但行为(和签名)不知怎么地从Java SE 1.4.2(文档现在存档)改变到8,我在web上找到的大多数代码片段都使用1.4.2行为。

例如:

int[] numbers = new int[] { 1, 2, 3 };
Arrays.asList(numbers)

在1.4.2返回一个包含元素1,2,3的列表 在1.5.0+上返回包含数组'numbers'的列表

在许多情况下,它应该很容易被发现,但有时它会被忽视:

Assert.assertTrue(Arrays.asList(numbers).indexOf(4) == -1);

当前回答

使用番石榴: Integer[] array = {1,2,3}; List<Integer> List = Lists.newArrayList(sourceArray); 使用Apache Commons Collections: Integer[] array = {1,2,3}; List<Integer> List = new ArrayList<>(6); CollectionUtils。addAll(列表、数组);

其他回答

Int是一个原语。原语不能接受空值,只能有默认值。因此,要接受null,您需要使用包装器类Integer。

选项1:

int[] nos = { 1, 2, 3, 4, 5 };
Integer[] nosWrapped = Arrays.stream(nos).boxed()   
                                        .toArray(Integer[]::new);
nosWrapped[5] = null // can store null

选项2: 您可以使用任何使用包装器类Integer的数据结构

int[] nos = { 1, 2, 3, 4, 5 };
List<Integer> = Arrays.asList(nos)

给定的数组:

    int[] givenArray = {2,2,3,3,4,5};

将整数数组转换为整数列表

一种方法:boxxed() ->返回IntStream

    List<Integer> givenIntArray1 = Arrays.stream(givenArray)
                                  .boxed()
                                  .collect(Collectors.toList());

第二种方法:将流的每个元素映射为Integer,然后收集

注意: 使用mapToObj你可以隐蔽每个int元素到字符串流,字符流等套管i (char)i

    List<Integer> givenIntArray2 = Arrays.stream(givenArray)
                                         .mapToObj(i->i)
                                         .collect(Collectors.toList());

将一个数组类型转换为另一个类型示例:

List<Character> givenIntArray2 = Arrays.stream(givenArray)
                                             .mapToObj(i->(char)i)
                                             .collect(Collectors.toList());

说到转换方式,这取决于你为什么需要你的列表。 如果你只需要读取数据。好的,给你:

Integer[] values = { 1, 3, 7 };
List<Integer> list = Arrays.asList(values);

但如果你这样做:

list.add(1);

你会得到java.lang.UnsupportedOperationException。 所以在某些情况下你甚至需要这个:

Integer[] values = { 1, 3, 7 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(values));

第一种方法实际上不转换数组,但“表示”它像一个列表。但是数组的所有属性都在底层,比如固定数量的元素。请注意,在构造ArrayList时需要指定类型。

我也遇到过同样的问题,写了一个泛型函数,它接受一个数组,并返回一个具有相同内容的相同类型的ArrayList:

public static <T> ArrayList<T> ArrayToArrayList(T[] array) {
    ArrayList<T> list = new ArrayList<T>();
    for(T elmt : array) list.add(elmt);
    return list;
}

我最近不得不将一个数组转换为List。稍后,程序过滤列表,试图删除数据。当你使用Arrays.asList(array)函数时,你创建了一个固定大小的集合:你既不能添加也不能删除。这篇文章比我更好地解释了这个问题:为什么当我试图从List中删除一个元素时,会得到一个UnsupportedOperationException ?

最后,我不得不做一个“手动”转换:

    List<ListItem> items = new ArrayList<ListItem>();
    for (ListItem item: itemsArray) {
        items.add(item);
    }

我想我可以使用list . addall (items)操作添加从数组到列表的转换。