ArrayList转化为基本类型int数组!
import java.util.ArrayList; import java.util.Random; public class Main { public static void main(String[] args) { ArrayList<Integer> arrayList = new ArrayList<>(); Random random = new Random(); int Len = 10000; for (int i = 0; i < Len; i++) { arrayList.add(random.nextInt()); } int[] ints = arrayList.stream().mapToInt(value -> 2 * value).toArray();
} }
IntStream mapToInt(ToIntFunction<? super T> mapper);
参数mapper是一个函数式接口!
ArrayList转化为包装类Interger数组!
import java.util.ArrayList;
import java.util.Random;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
Random random = new Random();
int Len = 10000;
for (int i = 0; i < Len; i++) {
arrayList.add(random.nextInt());
}
//方式一:public Object[] toArray(){...}
Object[] objects0 = arrayList.toArray();//方式一
//方式二:public <T> T[] toArray(T[] a){...}
Integer[] integers1 = arrayList.toArray(new Integer[arrayList.size()]);
Integer[] integers2 = arrayList.toArray(new Integer[0]);
//对比public Object[] toArray(){...} public <T> T[] toArray(T[] a){...}源码
//推荐方式
Integer[] integers3 = (Integer[]) arrayList.toArray();
}
}
基本类型数组转ArrayList!
public class Main { public static void main(String[] args) { int[] array = new int[10000000]; Random random = new Random(); for (int i = 0; i < array.length; i++) { array[i] = random.nextInt(); }
int cycle = 100; long begin = 0; long end = 0;
//方式1 begin = System.currentTimeMillis(); for (int i = 0; i < cycle; i++) { List<Integer> collect1 =new ArrayList<>(array.length); for (int k = 0; k < array.length; k++) { collect1.add(array[k]); } collect1 = null; } end = System.currentTimeMillis(); System.out.printf("(end - begin)*1.0/cycle:%.6f ",(end - begin)*1.0/cycle); //方式2 begin = System.currentTimeMillis(); for (int i = 0; i < cycle; i++) { List<Integer> collect0 = Arrays.stream(array).boxed().collect(Collectors.toList()); collect0 = null; } end = System.currentTimeMillis(); System.out.printf("(end - begin)*1.0/cycle:%.6f ",(end - begin)*1.0/cycle); } }
比较结果:
从结果可以看出:方式1明显快于方式2!
包装类型Interger数组转ArrayList!
Arrays.asList()!