如何将 Java 8 Stream 转换为数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23079003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a Java 8 Stream to an Array?
提问by
What is the easiest/shortest way to convert a Java 8 Stream
into an array?
将 Java 8Stream
转换为数组的最简单/最短的方法是什么?
采纳答案by skiwi
The easiest method is to use the toArray(IntFunction<A[]> generator)
method with an array constructor reference. This is suggested in the API documentation for the method.
最简单的方法是使用toArray(IntFunction<A[]> generator)
带有数组构造函数引用的方法。方法的API 文档中建议了这一点。
String[] stringArray = stringStream.toArray(String[]::new);
What it does is find a method that takes in an integer (the size) as argument, and returns a String[]
, which is exactly what (one of the overloads of) new String[]
does.
它所做的是找到一个方法,它接受一个整数(大小)作为参数,并返回一个String[]
,这正是(的重载之一)new String[]
所做的。
You could also write your own IntFunction
:
你也可以自己写IntFunction
:
Stream<String> stringStream = ...;
String[] stringArray = stringStream.toArray(size -> new String[size]);
The purpose of the IntFunction<A[]> generator
is to convert an integer, the size of the array, to a new array.
的目的IntFunction<A[]> generator
是将一个整数(数组的大小)转换为一个新数组。
Example code:
示例代码:
Stream<String> stringStream = Stream.of("a", "b", "c");
String[] stringArray = stringStream.toArray(size -> new String[size]);
Arrays.stream(stringArray).forEach(System.out::println);
Prints:
印刷:
a
b
c
回答by Ida Buci?
If you want to get an array of ints, with values form 1 to 10, from a Stream, there is IntStream at your disposal.
如果您想从 Stream 中获取一个整数数组,其值从 1 到 10,则可以使用 IntStream。
Here we create a Stream with a Stream.of method and convert an Stream to an IntStream using a mapToInt. Then we can call IntStream's toArray method.
在这里,我们使用 Stream.of 方法创建一个 Stream,并使用 mapToInt 将一个 Stream 转换为 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();
Here is the same thing, without the Stream, using only the IntStream
这是同样的事情,没有 Stream,只使用 IntStream
int[]array2 = IntStream.rangeClosed(1, 10).toArray();
回答by Thomas Pliakas
You can create a custom collector that convert a stream to array.
您可以创建一个将流转换为数组的自定义收集器。
public static <T> Collector<T, ?, T[]> toArray( IntFunction<T[]> converter )
{
return Collectors.collectingAndThen(
Collectors.toList(),
list ->list.toArray( converter.apply( list.size() ) ) );
}
and a quick use
和快速使用
List<String> input = Arrays.asList( ..... );
String[] result = input.stream().
.collect( CustomCollectors.**toArray**( String[]::new ) );
回答by Sagar Mal Shankhala
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
Integer[] integers = stream.toArray(it->new Integer[it]);
回答by Bachiri Taoufiq Abderrahman
You can convert a java 8 stream to an array using this simple code block:
您可以使用这个简单的代码块将 java 8 流转换为数组:
String[] myNewArray3 = myNewStream.toArray(String[]::new);
But let's explain things more, first, let's Create a list of string filled with three values:
但是让我们更详细地解释一下,首先,让我们创建一个填充了三个值的字符串列表:
String[] stringList = {"Bachiri","Taoufiq","Abderrahman"};
Create a stream from the given Array :
从给定的 Array 创建一个流:
Stream<String> stringStream = Arrays.stream(stringList);
we can now perform some operations on this stream Ex:
我们现在可以对这个流执行一些操作,例如:
Stream<String> myNewStream = stringStream.map(s -> s.toUpperCase());
and finally convert it to a java 8 Array using these methods:
最后使用以下方法将其转换为 java 8 数组:
1-Classic method (Functional interface)
1-经典方法(Functional interface)
IntFunction<String[]> intFunction = new IntFunction<String[]>() {
@Override
public String[] apply(int value) {
return new String[value];
}
};
String[] myNewArray = myNewStream.toArray(intFunction);
2 -Lambda expression
2 -Lambda 表达式
String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);
3- Method reference
3- 方法参考
String[] myNewArray3 = myNewStream.toArray(String[]::new);
Method reference Explanation:
方法参考说明:
It's another way of writing a lambda expression that it's strictly equivalent to the other.
这是编写 lambda 表达式的另一种方式,它严格等同于另一个。
回答by Kunda
Using the toArray(IntFunction<A[]> generator)
method is indeed a very elegant and safe way to convert (or more correctly, collect) a Stream into an array of the same type of the Stream.
使用该toArray(IntFunction<A[]> generator)
方法确实是一种非常优雅且安全的方式,可以将 Stream 转换(或更准确地说,是收集)Stream 为与 Stream 类型相同的数组。
However, if the returned array's type is not important, simply using the toArray()
method is both easier andshorter.
For example:
但是,如果返回数组的类型并不重要,那么简单地使用该toArray()
方法既简单又简短。例如:
Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
System.out.printf("%s, %s, %s!", args.toArray());
回答by Danail Tsvetanov
Convert text to string array where separating each value by comma, and trim every field, for example:
将文本转换为字符串数组,其中用逗号分隔每个值,并修剪每个字段,例如:
String[] stringArray = Arrays.stream(line.split(",")).map(String::trim).toArray(String[]::new);
回答by raja emani
You can do it in a few ways.All the ways are technically the same but using Lambda would simplify some of the code. Lets say we initialize a List first with String, call it persons.
您可以通过几种方式来实现。所有方式在技术上都是相同的,但使用 Lambda 会简化一些代码。假设我们首先用字符串初始化一个列表,称之为人。
List<String> persons = new ArrayList<String>(){{add("a"); add("b"); add("c");}};
Stream<String> stream = persons.stream();
Now you can use either of the following ways.
现在您可以使用以下任一方式。
Using the Lambda Expresiion to create a new StringArray with defined size.
String[] stringArray = stream.toArray(size->new String[size]);
Using the method reference directly.
String[] stringArray = stream.toArray(String[]::new);
使用 Lambda 表达式创建具有定义大小的新 StringArray。
String[] stringArray = stream.toArray(size->new String[size]);
直接使用方法引用。
String[] stringArray = stream.toArray(String[]::new);
回答by Raj N
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
int[] arr= stream.mapToInt(x->x.intValue()).toArray();
回答by Sma Ma
import java.util.List;
import java.util.stream.Stream;
class Main {
public static void main(String[] args) {
// Create a stream of strings from list of strings
Stream<String> myStreamOfStrings = List.of("lala", "foo", "bar").stream();
// Convert stream to array by using toArray method
String[] myArrayOfStrings = myStreamOfStrings.toArray(String[]::new);
// Print results
for (String string : myArrayOfStrings) {
System.out.println(string);
}
}
}
Try it out online: https://repl.it/@SmaMa/Stream-to-array