Java8 基本类型数组转换为List

Java 8种基本类型(byte/short/int/long/float/double/char/boolean)的数组(byte[]/short[]/int[]/long[]/float[]/double[]/char[]/boolean[])不能直接通过Arrays.asList方法转换为List,因为List的元素必须是包装类。在Java8之前,想要实现这种转换只能通过循环,Java8提供的新特性Stream则可以让我们在一行之内解决这个问题。

list = Arrays.stream(arrays).boxed().collect(Collectors.toList());

其中Arrays.stream方法把数组转换为Stream对象,Stream.boxed方法把基本类型转换为包装类,最后调用Stream.collect方法将Stream对象转换为List对象。

Example:

import java.util.*;
import java.util.stream.Collectors;

class Main1 {
    public static void main(String[] args)
    {
        int[] arrays = {1,2,3};
        List<Integer> list = Arrays.stream(arrays).boxed().collect(Collectors.toList());
        System.out.println(list);
    }
}

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/89087076
今日推荐