如何在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);

当前回答

为了解决这个问题,我开始尝试减少准备一些测试用例输入的代码量。我看到很多人试图在Arrays.asList()中包含高级和新特性,但下面的代码选择了简单性:

    //Integer input[]
    List<Integer> numbers = Arrays.asList(new Integer[]{1, 2 ,3, 4, 5, 4, 3, 2, 1, 3, 4});
    
    //String input[]
    List<String> names = Arrays.asList(new String[]{"Jhon", "Lucas", "Daniel", "Jim", "Sam"});
    
    //String input[]
    List<Character> letters = Arrays.asList(new Character[]{'A', 'B', 'K', 'J', 'F'});
    

请注意,匿名数组示例只适用于非基本类型的数组,因为API使用泛型,这就是为什么你可以看到几个2行示例,更多信息在这里:为什么Java泛型不支持基本类型?

对于较新的jdk,还有另一个更简单的选择,下面的例子与上面展示的例子相同:

    //Integer
    List<Integer> numbers = Arrays.asList(1, 2 ,3, 4, 5, 4, 3, 2, 1, 3, 4);
    
    //String
    List<String> names = Arrays.asList("Jhon", "Lucas", "Daniel", "Jim", "Sam"); 
    
    //Character
    List<Character> letters = Arrays.asList('A', 'B', 'K', 'J', 'F');

其他回答

在Java 9中,您可以通过新的方便的工厂方法List.of使用更优雅的不可变列表:

List<String> immutableList = List.of("one","two","three");

(无耻地从这里抄袭)

如果你使用Apache common -lang,另一个解决方法是:

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

ArrayUtils的地方。toObject将int[]转换为Integer[]

更短:

List<Integer> list = Arrays.asList(1, 2, 3, 4);

你能不能改进这个答案,因为这是我使用的,但我不是100%清楚。它工作正常,但intelliJ增加了新的气象站[0]。为什么是0 ?

公共气象站[]removeElementAtIndex(气象站[]数组,int索引) { List<WeatherStation> List = new ArrayList<WeatherStation>(Arrays.asList(array)); list.remove(指数); 返回列表。toArray(新WeatherStation [0]); }

给定的数组:

    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());