Java中List, Integer[], int[]的相互转换
有时候list和数组int[]转换很麻烦。
List和String[]也同理。难道每次非得写一个循环遍历吗?其实一步就可以搞定。
本文涉及到一些Java8的特性。如果没有接触过就先学会怎么用,然后再细细研究。
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
int[] data = {4, 5, 3, 6, 2, 5, 1};
// int[] 转 List
List list1 = Arrays.stream(data).boxed().collect(Collectors.toList());
// Arrays.stream(arr) 可以替换成IntStream.of(arr)。
// 1.使用Arrays.stream将int[]转换成IntStream。
// 2.使用IntStream中的boxed()装箱。将IntStream转换成Stream。
// 3.使用Stream的collect(),将Stream转换成List,因此正是List。
// int[] 转 Integer[]
Integer[] integers1 = Arrays.stream(data).boxed().toArray(Integer[]::new);
// 前两步同上,此时是Stream。
// 然后使用Stream的toArray,传入IntFunction generator。
// 这样就可以返回Integer数组。
// 不然默认是Object[]。
// List 转 Integer[]
Integer[] integers2 = list1.toArray(new Integer[0]);
// 调用toArray。传入参数T[] a。这种用法是目前推荐的。
// List转String[]也同理。
// List 转 int[]
int[] arr1 = list1.stream().mapToInt(Integer::valueOf).toArray();
// 想要转换成int[]类型,就得先转成IntStream。
// 这里就通过mapToInt()把Stream调用Integer::valueOf来转成IntStream
// 而IntStream中默认toArray()转成int[]。
// Integer[] 转 int[]
int[] arr2 = Arrays.stream(integers1).mapToInt(Integer::valueOf).toArray();
// 思路同上。先将Integer[]转成Stream,再转成IntStream。
// Integer[] 转 List
List list2 = Arrays.asList(integers1);
// 最简单的方式。String[]转List也同理。
// 同理
String[] strings1 = {"a", "b", "c"};
// String[] 转 List
List list3 = Arrays.asList(strings1);
// List 转 String[]
String[] strings2 = list3.toArray(new String[0]);
}
}
打印数组
Object[] paramValues;
for (int i = 0; i < paramValues.length; i++) {
System.out.print(paramValues[i] + ", ");
}
for(Object n: paramValues)
System.out.println(n+", ");
System.out.println( Arrays.toString(paramValues) );
System.out.println(Arrays.asList(paramValues));
Arrays.asList(arr).stream().forEach(s -> System.out.println(s));//java8