将数组/字符串列表转换为数组/整数列表的 Lambda 表达式 [英] Lambda expression to convert array/List of String to array/List of Integers

查看:38
本文介绍了将数组/字符串列表转换为数组/整数列表的 Lambda 表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 Java 8 带有强大的 lambda 表达式,

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.

推荐答案

您可以创建辅助方法,将 T 类型的列表(数组)转换为 类型的列表(数组)>U 使用 mapstream.

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 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆