1.Java(基本数据类型)数组转List简述
2.List转Java(基本数据类型)数组简述
3.List<String>转为String[]数组,String[]数组转为List<String>
数组转LIST:
为了方便大家copy,简单
若是包装类(Integer,Long,Double)或String等数组转list
String[] temp = new String[3];
temp[0] = “1”;
temp[1] = “2”;
temp[2] = “3”;
第一种方法: List<String> listA = Arrays.asList(temp)
这种方法数组转成的listA,不能对List增删,只能查改,否则抛异常。
使用场景:Arrays.asList(strArray)方式仅能用在将数组转换为List后,不需要增删其中的值,仅作为数据源读取使用。
第二种方法: List<String> listB = new ArrayList(Arrays.asList(temp));
通过ArrayList的构造器,将Arrays.asList(strArray)的返回值由java.util.Arrays.ArrayList转为java.util.ArrayList,支持增删改查的方式
使用场景:需要在将数组转换为List后,对List进行增删改查操作,在List的数据量不大的情况下,可以使用。
第三种方法: 1. List<String> listC = new ArrayList<>(temp.length);
2. Collections.addAll(listC,temp);
通过Collections.addAll(arrayList, strArray)方式转换,根据数组的长度创建一个长度相同的List,然后通过Collections.addAll()方法,将数组中的元素转为二进制,然后添加到List中,这是最高效的方法。
使用场景:需要在将数组转换为List后,对List进行增删改查操作,在List的数据量巨大(1W+)的情况下,优先使用,可以提高操作速度。
第四种方法: Stream的更优写法,以及boxed封装
int[] a = new int[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
System.out.println(list);
long[] b = new long[3];
b[0] = 1L;
b[1] = 2L;
b[2] = 3L;
List<Long> longList= Arrays.stream(b).boxed().collect(Collectors.toList());
System.out.println(longList);
double[] c = new double[3];
c[0] = 1.1;
c[1] = 21.1;
c[2] = 31.1;
List<Double> doubleList= Arrays.stream(c).boxed().collect(Collectors.toList());
System.out.println(doubleList);
String[] temp = new String[3];
temp[0] = "1";
temp[1] = "2";
temp[2] = "3";
Stream<String> stream = Arrays.stream(temp);
List<String> list = stream.collect(Collectors.toList());
System.out.println(list);
简而言之:
int(Integer)=>Integer: List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
long(Long)=>Long: List<Long> list = Arrays.stream(b).boxed().collect(Collectors.toList());
double(Double)=>Double: List<Double> list = Arrays.stream(c).boxed().collect(Collectors.toList());
String=>String Arrays.stream(temp).collect(Collectors.toList())