将Java 8流转换为数组的最简单/最短的方法是什么?
当前回答
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
int[] arr= stream.mapToInt(x->x.intValue()).toArray();
其他回答
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
int[] arr= stream.mapToInt(x->x.intValue()).toArray();
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
Integer[] integers = stream.toArray(it->new Integer[it]);
将文本转换为字符串数组,其中用逗号分隔每个值,并修剪每个字段,例如:
String[] stringArray = Arrays.stream(line.split(","))
.map(String::trim)
.toArray(String[]::new);
您可以创建一个将流转换为数组的自定义收集器。
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 ) );
如果你想从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();
推荐文章
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 向对象数组添加属性
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap
- web - inf在Java EE web应用程序中用于什么?
- Java 8: Lambda-Streams,过滤方法与异常
- 将JsonNode转换为POJO
- 如何查看IntelliJ中的编译错误列表?
- Java SimpleDateFormat("yyyy-MM-dd' t ' hh:mm:ss' z '")给出的时区为IST
- 杰克逊克服下划线,支持骆驼案
- List、List<?>, List<T>, List<E>, List<Object>
- JavaScript在数组中