将Java 8流转换为数组的最简单/最短的方法是什么?


当前回答

将文本转换为字符串数组,其中用逗号分隔每个值,并修剪每个字段,例如:

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

其他回答

     Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);

     Integer[] integers = stream.toArray(it->new Integer[it]);

您可以创建一个将流转换为数组的自定义收集器。

public static <T> Collector<T, ?, T[]> toArray( IntFunction<T[]> converter )
{
    return Collectors.collectingAndThen( 
                  Collectors.toList(), 
                  list ->list.toArray( converter.apply( list.size() ) ) );
}

快速使用

List<String> input = Arrays.asList( ..... );

String[] result = input.stream().
         .collect( CustomCollectors.**toArray**( String[]::new ) );

将文本转换为字符串数组,其中用逗号分隔每个值,并修剪每个字段,例如:

String[] stringArray = Arrays.stream(line.split(","))          
                             .map(String::trim)
                             .toArray(String[]::new);
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);

int[] arr=   stream.mapToInt(x->x.intValue()).toArray();

如果你想从Stream<Integer>中获得一个整数数组,值从1到10,有IntStream供你使用。

这里我们用一个流创建了一个流。方法,使用mapToInt将Stream<Integer>转换为IntStream。然后我们可以调用IntStream的toArray方法。

Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10);
//or use this to create our stream 
//Stream<Integer> stream = IntStream.rangeClosed(1, 10).boxed();
int[] array =  stream.mapToInt(x -> x).toArray();

这里是同样的事情,没有Stream<Integer>,只使用IntStream:

int[]array2 =  IntStream.rangeClosed(1, 10).toArray();