整数的LAMBDA前pression转换字符串数组/列表数组/列表 [英] Lambda expression to convert array/List of String to array/List of Integers
本文介绍了整数的LAMBDA前pression转换字符串数组/列表数组/列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于Java 8自带功能强大的lambda前pressions,
Since Java 8 comes with powerful lambda expressions,
我想编写一个函数字符串列表/数组转换为整数数组/列表,花车,双打等。
I would like to write a function to convert a List/array of Strings to array/List of Integers, Floats, Doubles etc..
在普通Java,这将是为
In normal Java, it would be as simple as
for(String str : strList){
intList.add(Integer.valueOf(str));
}
但我怎么实现与一个lambda给出一个字符串数组转换为整数数组。同样的,
But how do I achieve the same with a lambda, given an array of Strings to be converted to an array of Integers.
推荐答案
您可以创建的helper方法,将键入 T
的列表(数组)转换到一个列表(类型的数组) U
使用 地图
上的 流
。
You could create helper methods that would convert a list (array) of type T
to a list (array) of type U
using the map
operation on stream
.
//for lists
public static <T, U> List<U> convertList(List<T> from, Function<T, U> func){
return from.stream().map(func).collect(Collectors.toList());
}
//for arrays
public static <T, U> U[] convertArray(T[] from, Function<T, U> func,
IntFunction<U[]> generator){
return Arrays.stream(from).map(func).toArray(generator);
}
和使用这样的:
//for lists
List<String> stringList = Arrays.asList("1","2","3");
List<Integer> integerList = convertList(stringList, s -> Integer.parseInt(s));
//for arrays
String[] stringArr = {"1","2","3"};
Double[] doubleArr = convertArray(stringArr, Double::parseDouble, Double[]::new);
需要注意的是
秒 - &GT;的Integer.parseInt(S)
可以与被替换整数:: parseInt函数
(见的方法引用的)
这篇关于整数的LAMBDA前pression转换字符串数组/列表数组/列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文