Java stream toArray() convert to a specific type of array

后端 未结 2 1512
轮回少年
轮回少年 2020-12-08 01:43

Maybe this is very simple but I\'m actually a noob on Java 8 features and don\'t know how to accomplish this. I have this simple line that contains the following text:

2条回答
  •  不思量自难忘°
    2020-12-08 02:26

    Use toArray(size -> new String[size]) or toArray(String[]::new).

    String[] strings = Arrays.stream(line.split(",")).map(String::trim).toArray(String[]::new);
    

    This is actually a lambda expression for

    .toArray(new IntFunction() {
            @Override
            public String[] apply(int size) {
                return new String[size];
            }
        });
    

    Where you are telling convert the array to a String array of same size.

    From the docs

    The generator function takes an integer, which is the size of the desired array, and produces an array of the desired size. This can be concisely expressed with an array constructor reference:

     Person[] men = people.stream()
                          .filter(p -> p.getGender() == MALE)
                          .toArray(Person[]::new);
    

    Type Parameters:

    A - the element type of the resulting array

    Parameters:

    generator - a function which produces a new array of the desired type and the provided length

提交回复
热议问题