Lambda表达式将数组/ List of String转换为数组/ List of Integers [英] Lambda expression to convert array/List of String to array/List of Integers
问题描述
由于Java 8具有强大的lambda表达式,
Since Java 8 comes with powerful lambda expressions,
我想编写一个函数来将字符串的List /数组转换为数组/ ,Doubles等。
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.
推荐答案
您可以创建帮助方法来转换类型为<使用 T 添加到类型为 U
的列表net / lambda / b78 / docs / api / java / util / stream / Stream.html#map%28java.util.function.Function%29> map
操作 流
。
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);
请注意
s - > Integer.parseInt(s)
可以替换为 Integer :: parseInt
(请参阅方法参考)
Note that
s -> Integer.parseInt(s)
could be replaced with Integer::parseInt
(see Method references)
这篇关于Lambda表达式将数组/ List of String转换为数组/ List of Integers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!