Java Stream 常用数组类型转换用法

业务目前经常会使用的stream流来处理数据,特别是对数组的类型进行转换,下面我分类总结常用的转换用法

 1.字符串数组 --》 数值型数组 int、Long、Double

String[] str = new String[]{"1","2","3","4","5","6"};
int[] ints = Arrays.stream(str).mapToInt(Integer::valueOf).toArray();
long[] longs = Arrays.stream(str).mapToLong(Long::valueOf).toArray();
double[] doubles = Arrays.stream(str).mapToDouble(Double::valueOf).toArray();

延伸一点,一般我们String数组元素是数字内容才需要转数值型,则可以通过sum函数进行求和

int sums = Arrays.stream(str).mapToInt(Integer::valueOf).sum();

2.字符串数组 --》List 、List、List

String[] str = new String[]{"1","2","3","4","5","6"};
List list1 = Arrays.stream(str).map(Integer::valueOf).collect(Collectors.toList());
List list2 = Arrays.stream(str).map(Long::valueOf).collect(Collectors.toList());
List list3 = Arrays.stream(str).map(Double::valueOf).collect(Collectors.toList());

 3.数值型数组 --》int、Long、Double字符串数组 

String[] strArr1 = Arrays.stream(ints).mapToObj(String::valueOf).toArray(String[]::new);
String[] strArr2 = Arrays.stream(longs).mapToObj(String::valueOf).toArray(String[]::new);
String[] strArr3 = Arrays.stream(doubles).mapToObj(String::valueOf).toArray(String[]::new);

你可能感兴趣的:(业务场景实例问题,Java,Java,Stream高效数据处理,java,后端)