Lambda expression to convert array/List of String

2020-01-24 02:17发布

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..

In normal Java, it would be as simple as

for(String str : strList){
   intList.add(Integer.valueOf(str));
}

But how do I achieve the same with a lambda, given an array of Strings to be converted to an array of Integers.

9条回答
聊天终结者
2楼-- · 2020-01-24 02:39

You can also use,

List<String> list = new ArrayList<>();
    list.add("1");
    list.add("2");
    list.add("3");

    Integer[] array = list.stream()
        .map( v -> Integer.valueOf(v))
        .toArray(Integer[]::new);
查看更多
Juvenile、少年°
3楼-- · 2020-01-24 02:40
List<Integer> intList = strList.stream()
                               .map(Integer::valueOf)
                               .collect(Collectors.toList());
查看更多
萌系小妹纸
4楼-- · 2020-01-24 02:41

In addition - control when string array doesn't have elements:

Arrays.stream(from).filter(t -> (t != null)&&!("".equals(t))).map(func).toArray(generator) 
查看更多
戒情不戒烟
5楼-- · 2020-01-24 02:46

For List :

List<Integer> intList 
 = stringList.stream().map(Integer::valueOf).collect(Collectors.toList());

For Array :

int[] intArray = Arrays.stream(stringArray).mapToInt(Integer::valueOf).toArray();
查看更多
家丑人穷心不美
6楼-- · 2020-01-24 02:49

Arrays.toString(int []) works for me.

查看更多
放荡不羁爱自由
7楼-- · 2020-01-24 02:52

EDIT: As pointed out in the comments, this is a much simpler version: Arrays.stream(stringArray).mapToInt(Integer::parseInt).toArray() This way we can skip the whole conversion to and from a list.


I found another one line solution, but it's still pretty slow (takes about 100 times longer than a for cycle - tested on an array of 6000 0's)

String[] stringArray = ...
int[] out= Arrays.asList(stringArray).stream().map(Integer::parseInt).mapToInt(i->i).toArray();

What this does:

  1. Arrays.asList() converts the array to a List
  2. .stream converts it to a Stream (needed to perform a map)
  3. .map(Integer::parseInt) converts all the elements in the stream to Integers
  4. .mapToInt(i->i) converts all the Integers to ints (you don't have to do this if you only want Integers)
  5. .toArray() converts the Stream back to an array
查看更多
登录 后发表回答