How to Convert a Java 8 Stream to an Array?initialize an array by using casted lambda expressionsSimpliest way to convert array of Integer to array of String in Java 8how to convert List of Integer to Array of Strings using Java 8 apiJAVA8: Map list of objects to String[]How do Java 8 array constructor references work?Why do the new Java 8 streams return an Object Array on toArray calls?Converting List to Two dimensional array Java for TestNG data providerJava 8 Streams - Collecting Values that could be nullInstantiating array of objects with streamsUsing filter in streamsIs Java “pass-by-reference” or “pass-by-value”?How can I concatenate two arrays in Java?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How do I read / convert an InputStream into a String in Java?How do I declare and initialize an array in Java?Loop through an array in JavaScriptHow do I convert a String to an int in Java?How do I remove a particular element from an array in JavaScript?Why is it faster to process a sorted array than an unsorted array?
Simple image editor tool to draw a simple box/rectangle in an existing image
Greatest common substring
Why are all the doors on Ferenginar (the Ferengi home world) far shorter than the average Ferengi?
Can I rely on these GitHub repository files?
What will be the benefits of Brexit?
No idea how to draw this using tikz
Should my PhD thesis be submitted under my legal name?
Pronouncing Homer as in modern Greek
Indicating multiple different modes of speech (fantasy language or telepathy)
Hostile work environment after whistle-blowing on coworker and our boss. What do I do?
Adding empty element to declared container without declaring type of element
Resetting two CD4017 counters simultaneously, only one resets
Why are on-board computers allowed to change controls without notifying the pilots?
Can I create an upright 7-foot × 5-foot wall with the Minor Illusion spell?
How do I repair my stair bannister?
Lifted its hind leg on or lifted its hind leg towards?
Can I use my Chinese passport to enter China after I acquired another citizenship?
Is it okay / does it make sense for another player to join a running game of Munchkin?
Books on the History of math research at European universities
Meta programming: Declare a new struct on the fly
Is exact Kanji stroke length important?
What is the term when two people sing in harmony, but they aren't singing the same notes?
The most efficient algorithm to find all possible integer pairs which sum to a given integer
Why is delta-v is the most useful quantity for planning space travel?
How to Convert a Java 8 Stream to an Array?
initialize an array by using casted lambda expressionsSimpliest way to convert array of Integer to array of String in Java 8how to convert List of Integer to Array of Strings using Java 8 apiJAVA8: Map list of objects to String[]How do Java 8 array constructor references work?Why do the new Java 8 streams return an Object Array on toArray calls?Converting List to Two dimensional array Java for TestNG data providerJava 8 Streams - Collecting Values that could be nullInstantiating array of objects with streamsUsing filter in streamsIs Java “pass-by-reference” or “pass-by-value”?How can I concatenate two arrays in Java?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How do I read / convert an InputStream into a String in Java?How do I declare and initialize an array in Java?Loop through an array in JavaScriptHow do I convert a String to an int in Java?How do I remove a particular element from an array in JavaScript?Why is it faster to process a sorted array than an unsorted array?
What is the easiest/shortest way to convert a Java 8 Stream
into an array?
java arrays java-8 java-stream
add a comment |
What is the easiest/shortest way to convert a Java 8 Stream
into an array?
java arrays java-8 java-stream
2
I'd suggest you to revert the rollback as the question was more complete and showed you had tried something.
– skiwi
Apr 15 '14 at 9:13
2
@skiwi Thanks! but i thought the attempted code does not really add more information to the question, and nobody has screamed "show us your attempt" yet =)
– user972946
Apr 15 '14 at 9:20
17
@skiwi: Although I usually shout at the do-my-homework-instead-of-me questions, this particular question seems to be clearer to me without any additional mess. Let's keep it tidy.
– Honza Zidek
Apr 16 '14 at 11:21
add a comment |
What is the easiest/shortest way to convert a Java 8 Stream
into an array?
java arrays java-8 java-stream
What is the easiest/shortest way to convert a Java 8 Stream
into an array?
java arrays java-8 java-stream
java arrays java-8 java-stream
edited Dec 28 '15 at 5:46
vaxquis
7,74853958
7,74853958
asked Apr 15 '14 at 9:00
user972946
2
I'd suggest you to revert the rollback as the question was more complete and showed you had tried something.
– skiwi
Apr 15 '14 at 9:13
2
@skiwi Thanks! but i thought the attempted code does not really add more information to the question, and nobody has screamed "show us your attempt" yet =)
– user972946
Apr 15 '14 at 9:20
17
@skiwi: Although I usually shout at the do-my-homework-instead-of-me questions, this particular question seems to be clearer to me without any additional mess. Let's keep it tidy.
– Honza Zidek
Apr 16 '14 at 11:21
add a comment |
2
I'd suggest you to revert the rollback as the question was more complete and showed you had tried something.
– skiwi
Apr 15 '14 at 9:13
2
@skiwi Thanks! but i thought the attempted code does not really add more information to the question, and nobody has screamed "show us your attempt" yet =)
– user972946
Apr 15 '14 at 9:20
17
@skiwi: Although I usually shout at the do-my-homework-instead-of-me questions, this particular question seems to be clearer to me without any additional mess. Let's keep it tidy.
– Honza Zidek
Apr 16 '14 at 11:21
2
2
I'd suggest you to revert the rollback as the question was more complete and showed you had tried something.
– skiwi
Apr 15 '14 at 9:13
I'd suggest you to revert the rollback as the question was more complete and showed you had tried something.
– skiwi
Apr 15 '14 at 9:13
2
2
@skiwi Thanks! but i thought the attempted code does not really add more information to the question, and nobody has screamed "show us your attempt" yet =)
– user972946
Apr 15 '14 at 9:20
@skiwi Thanks! but i thought the attempted code does not really add more information to the question, and nobody has screamed "show us your attempt" yet =)
– user972946
Apr 15 '14 at 9:20
17
17
@skiwi: Although I usually shout at the do-my-homework-instead-of-me questions, this particular question seems to be clearer to me without any additional mess. Let's keep it tidy.
– Honza Zidek
Apr 16 '14 at 11:21
@skiwi: Although I usually shout at the do-my-homework-instead-of-me questions, this particular question seems to be clearer to me without any additional mess. Let's keep it tidy.
– Honza Zidek
Apr 16 '14 at 11:21
add a comment |
9 Answers
9
active
oldest
votes
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.
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.
You could also write your own 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.
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
7
and here is an explanation why and how the Array constructor reference actually work: stackoverflow.com/questions/29447561/…
– jarek.jpa
Sep 12 '16 at 18:16
"Zenexer is right, the solution should be: stream.toArray(String[]::new);" ... Well ok, but one should understand that the method reference is logically and functionally equivalent totoArray(sz -> new String[sz])
so I'm not sure that one can really say what the solution should or must be.
– scottb
Apr 20 '17 at 14:16
3
@scottbsz -> new String[sz]
makes a new function where as the constructor reference does not. It depends how much you value Garbage Collection Churn I guess.
– WORMSS
Aug 18 '17 at 9:19
3
@WORMSS It does not. It (statically!) makes a new,private
method, which cannot cause churn, and both versions need to create a new object. A reference creates an object that points directly at the target method; a lambda creates an object that points at the generatedprivate
one. A reference to a constructor should still perform better for lack of indirection and easier VM optimization, but churning has nothing to do with it.
– HTNW
Oct 29 '17 at 23:54
2
@HTNW you are correct, my apologise. It was infact my attempt to debug that was causing the churn that was causing the churn the first time I tried to do this, so I have had it stuck in my head that this is how it was. (Hate it when that happens).
– WORMSS
Oct 30 '17 at 8:38
|
show 1 more comment
If you want to get an array of ints, with values form 1 to 10, from a Stream, there is IntStream at your disposal.
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<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
int[]array2 = IntStream.rangeClosed(1, 10).toArray();
add a comment |
You can convert a java 8 stream to an array using this simple code block:
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 :
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:
1-Classic method (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
String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);
3- Method reference
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.
add a comment |
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 ) );
4
Why would you use this instead of Stream.toArray(IntFunction)?
– Didier L
May 31 '18 at 12:41
I needed a collector to pass to the 2-argCollectors.groupingBy
so that I could map some attribute to arrays of objects per attribute value. This answer gives me exactly that. Also @DidierL.
– Ole V.V.
Dec 9 '18 at 13:34
add a comment |
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);
add a comment |
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.
However, if the returned array's type is not important, simply using the toArray()
method is both easier and shorter.
For example:
Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
System.out.printf("%s, %s, %s!", args.toArray());
add a comment |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
Integer[] integers = stream.toArray(it->new Integer[it]);
add a comment |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
int[] arr= stream.mapToInt(x->x.intValue()).toArray();
add a comment |
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.
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);
add a comment |
protected by cassiomolin Mar 8 at 8:21
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.
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.
You could also write your own 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.
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
7
and here is an explanation why and how the Array constructor reference actually work: stackoverflow.com/questions/29447561/…
– jarek.jpa
Sep 12 '16 at 18:16
"Zenexer is right, the solution should be: stream.toArray(String[]::new);" ... Well ok, but one should understand that the method reference is logically and functionally equivalent totoArray(sz -> new String[sz])
so I'm not sure that one can really say what the solution should or must be.
– scottb
Apr 20 '17 at 14:16
3
@scottbsz -> new String[sz]
makes a new function where as the constructor reference does not. It depends how much you value Garbage Collection Churn I guess.
– WORMSS
Aug 18 '17 at 9:19
3
@WORMSS It does not. It (statically!) makes a new,private
method, which cannot cause churn, and both versions need to create a new object. A reference creates an object that points directly at the target method; a lambda creates an object that points at the generatedprivate
one. A reference to a constructor should still perform better for lack of indirection and easier VM optimization, but churning has nothing to do with it.
– HTNW
Oct 29 '17 at 23:54
2
@HTNW you are correct, my apologise. It was infact my attempt to debug that was causing the churn that was causing the churn the first time I tried to do this, so I have had it stuck in my head that this is how it was. (Hate it when that happens).
– WORMSS
Oct 30 '17 at 8:38
|
show 1 more comment
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.
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.
You could also write your own 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.
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
7
and here is an explanation why and how the Array constructor reference actually work: stackoverflow.com/questions/29447561/…
– jarek.jpa
Sep 12 '16 at 18:16
"Zenexer is right, the solution should be: stream.toArray(String[]::new);" ... Well ok, but one should understand that the method reference is logically and functionally equivalent totoArray(sz -> new String[sz])
so I'm not sure that one can really say what the solution should or must be.
– scottb
Apr 20 '17 at 14:16
3
@scottbsz -> new String[sz]
makes a new function where as the constructor reference does not. It depends how much you value Garbage Collection Churn I guess.
– WORMSS
Aug 18 '17 at 9:19
3
@WORMSS It does not. It (statically!) makes a new,private
method, which cannot cause churn, and both versions need to create a new object. A reference creates an object that points directly at the target method; a lambda creates an object that points at the generatedprivate
one. A reference to a constructor should still perform better for lack of indirection and easier VM optimization, but churning has nothing to do with it.
– HTNW
Oct 29 '17 at 23:54
2
@HTNW you are correct, my apologise. It was infact my attempt to debug that was causing the churn that was causing the churn the first time I tried to do this, so I have had it stuck in my head that this is how it was. (Hate it when that happens).
– WORMSS
Oct 30 '17 at 8:38
|
show 1 more comment
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.
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.
You could also write your own 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.
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
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.
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.
You could also write your own 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.
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
edited Aug 23 '18 at 17:09
Jens Bannmann
2,65743767
2,65743767
answered Apr 15 '14 at 9:07
skiwiskiwi
40.3k2598171
40.3k2598171
7
and here is an explanation why and how the Array constructor reference actually work: stackoverflow.com/questions/29447561/…
– jarek.jpa
Sep 12 '16 at 18:16
"Zenexer is right, the solution should be: stream.toArray(String[]::new);" ... Well ok, but one should understand that the method reference is logically and functionally equivalent totoArray(sz -> new String[sz])
so I'm not sure that one can really say what the solution should or must be.
– scottb
Apr 20 '17 at 14:16
3
@scottbsz -> new String[sz]
makes a new function where as the constructor reference does not. It depends how much you value Garbage Collection Churn I guess.
– WORMSS
Aug 18 '17 at 9:19
3
@WORMSS It does not. It (statically!) makes a new,private
method, which cannot cause churn, and both versions need to create a new object. A reference creates an object that points directly at the target method; a lambda creates an object that points at the generatedprivate
one. A reference to a constructor should still perform better for lack of indirection and easier VM optimization, but churning has nothing to do with it.
– HTNW
Oct 29 '17 at 23:54
2
@HTNW you are correct, my apologise. It was infact my attempt to debug that was causing the churn that was causing the churn the first time I tried to do this, so I have had it stuck in my head that this is how it was. (Hate it when that happens).
– WORMSS
Oct 30 '17 at 8:38
|
show 1 more comment
7
and here is an explanation why and how the Array constructor reference actually work: stackoverflow.com/questions/29447561/…
– jarek.jpa
Sep 12 '16 at 18:16
"Zenexer is right, the solution should be: stream.toArray(String[]::new);" ... Well ok, but one should understand that the method reference is logically and functionally equivalent totoArray(sz -> new String[sz])
so I'm not sure that one can really say what the solution should or must be.
– scottb
Apr 20 '17 at 14:16
3
@scottbsz -> new String[sz]
makes a new function where as the constructor reference does not. It depends how much you value Garbage Collection Churn I guess.
– WORMSS
Aug 18 '17 at 9:19
3
@WORMSS It does not. It (statically!) makes a new,private
method, which cannot cause churn, and both versions need to create a new object. A reference creates an object that points directly at the target method; a lambda creates an object that points at the generatedprivate
one. A reference to a constructor should still perform better for lack of indirection and easier VM optimization, but churning has nothing to do with it.
– HTNW
Oct 29 '17 at 23:54
2
@HTNW you are correct, my apologise. It was infact my attempt to debug that was causing the churn that was causing the churn the first time I tried to do this, so I have had it stuck in my head that this is how it was. (Hate it when that happens).
– WORMSS
Oct 30 '17 at 8:38
7
7
and here is an explanation why and how the Array constructor reference actually work: stackoverflow.com/questions/29447561/…
– jarek.jpa
Sep 12 '16 at 18:16
and here is an explanation why and how the Array constructor reference actually work: stackoverflow.com/questions/29447561/…
– jarek.jpa
Sep 12 '16 at 18:16
"Zenexer is right, the solution should be: stream.toArray(String[]::new);" ... Well ok, but one should understand that the method reference is logically and functionally equivalent to
toArray(sz -> new String[sz])
so I'm not sure that one can really say what the solution should or must be.– scottb
Apr 20 '17 at 14:16
"Zenexer is right, the solution should be: stream.toArray(String[]::new);" ... Well ok, but one should understand that the method reference is logically and functionally equivalent to
toArray(sz -> new String[sz])
so I'm not sure that one can really say what the solution should or must be.– scottb
Apr 20 '17 at 14:16
3
3
@scottb
sz -> new String[sz]
makes a new function where as the constructor reference does not. It depends how much you value Garbage Collection Churn I guess.– WORMSS
Aug 18 '17 at 9:19
@scottb
sz -> new String[sz]
makes a new function where as the constructor reference does not. It depends how much you value Garbage Collection Churn I guess.– WORMSS
Aug 18 '17 at 9:19
3
3
@WORMSS It does not. It (statically!) makes a new,
private
method, which cannot cause churn, and both versions need to create a new object. A reference creates an object that points directly at the target method; a lambda creates an object that points at the generated private
one. A reference to a constructor should still perform better for lack of indirection and easier VM optimization, but churning has nothing to do with it.– HTNW
Oct 29 '17 at 23:54
@WORMSS It does not. It (statically!) makes a new,
private
method, which cannot cause churn, and both versions need to create a new object. A reference creates an object that points directly at the target method; a lambda creates an object that points at the generated private
one. A reference to a constructor should still perform better for lack of indirection and easier VM optimization, but churning has nothing to do with it.– HTNW
Oct 29 '17 at 23:54
2
2
@HTNW you are correct, my apologise. It was infact my attempt to debug that was causing the churn that was causing the churn the first time I tried to do this, so I have had it stuck in my head that this is how it was. (Hate it when that happens).
– WORMSS
Oct 30 '17 at 8:38
@HTNW you are correct, my apologise. It was infact my attempt to debug that was causing the churn that was causing the churn the first time I tried to do this, so I have had it stuck in my head that this is how it was. (Hate it when that happens).
– WORMSS
Oct 30 '17 at 8:38
|
show 1 more comment
If you want to get an array of ints, with values form 1 to 10, from a Stream, there is IntStream at your disposal.
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<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
int[]array2 = IntStream.rangeClosed(1, 10).toArray();
add a comment |
If you want to get an array of ints, with values form 1 to 10, from a Stream, there is IntStream at your disposal.
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<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
int[]array2 = IntStream.rangeClosed(1, 10).toArray();
add a comment |
If you want to get an array of ints, with values form 1 to 10, from a Stream, there is IntStream at your disposal.
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<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
int[]array2 = IntStream.rangeClosed(1, 10).toArray();
If you want to get an array of ints, with values form 1 to 10, from a Stream, there is IntStream at your disposal.
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<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
int[]array2 = IntStream.rangeClosed(1, 10).toArray();
answered Oct 28 '16 at 13:28
Ida BucićIda Bucić
521510
521510
add a comment |
add a comment |
You can convert a java 8 stream to an array using this simple code block:
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 :
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:
1-Classic method (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
String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);
3- Method reference
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.
add a comment |
You can convert a java 8 stream to an array using this simple code block:
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 :
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:
1-Classic method (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
String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);
3- Method reference
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.
add a comment |
You can convert a java 8 stream to an array using this simple code block:
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 :
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:
1-Classic method (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
String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);
3- Method reference
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.
You can convert a java 8 stream to an array using this simple code block:
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 :
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:
1-Classic method (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
String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);
3- Method reference
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.
edited Jul 13 '17 at 17:04
answered May 25 '17 at 16:57
Bachiri Taoufiq AbderrahmanBachiri Taoufiq Abderrahman
1,38911322
1,38911322
add a comment |
add a comment |
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 ) );
4
Why would you use this instead of Stream.toArray(IntFunction)?
– Didier L
May 31 '18 at 12:41
I needed a collector to pass to the 2-argCollectors.groupingBy
so that I could map some attribute to arrays of objects per attribute value. This answer gives me exactly that. Also @DidierL.
– Ole V.V.
Dec 9 '18 at 13:34
add a comment |
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 ) );
4
Why would you use this instead of Stream.toArray(IntFunction)?
– Didier L
May 31 '18 at 12:41
I needed a collector to pass to the 2-argCollectors.groupingBy
so that I could map some attribute to arrays of objects per attribute value. This answer gives me exactly that. Also @DidierL.
– Ole V.V.
Dec 9 '18 at 13:34
add a comment |
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 ) );
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 ) );
answered Feb 16 '17 at 13:18
Thomas PliakasThomas Pliakas
693
693
4
Why would you use this instead of Stream.toArray(IntFunction)?
– Didier L
May 31 '18 at 12:41
I needed a collector to pass to the 2-argCollectors.groupingBy
so that I could map some attribute to arrays of objects per attribute value. This answer gives me exactly that. Also @DidierL.
– Ole V.V.
Dec 9 '18 at 13:34
add a comment |
4
Why would you use this instead of Stream.toArray(IntFunction)?
– Didier L
May 31 '18 at 12:41
I needed a collector to pass to the 2-argCollectors.groupingBy
so that I could map some attribute to arrays of objects per attribute value. This answer gives me exactly that. Also @DidierL.
– Ole V.V.
Dec 9 '18 at 13:34
4
4
Why would you use this instead of Stream.toArray(IntFunction)?
– Didier L
May 31 '18 at 12:41
Why would you use this instead of Stream.toArray(IntFunction)?
– Didier L
May 31 '18 at 12:41
I needed a collector to pass to the 2-arg
Collectors.groupingBy
so that I could map some attribute to arrays of objects per attribute value. This answer gives me exactly that. Also @DidierL.– Ole V.V.
Dec 9 '18 at 13:34
I needed a collector to pass to the 2-arg
Collectors.groupingBy
so that I could map some attribute to arrays of objects per attribute value. This answer gives me exactly that. Also @DidierL.– Ole V.V.
Dec 9 '18 at 13:34
add a comment |
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);
add a comment |
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);
add a comment |
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);
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);
edited Apr 2 '18 at 13:04
Lee Mac
5,48131643
5,48131643
answered Apr 2 '18 at 12:39
Danail TsvetanovDanail Tsvetanov
15516
15516
add a comment |
add a comment |
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.
However, if the returned array's type is not important, simply using the toArray()
method is both easier and shorter.
For example:
Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
System.out.printf("%s, %s, %s!", args.toArray());
add a comment |
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.
However, if the returned array's type is not important, simply using the toArray()
method is both easier and shorter.
For example:
Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
System.out.printf("%s, %s, %s!", args.toArray());
add a comment |
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.
However, if the returned array's type is not important, simply using the toArray()
method is both easier and shorter.
For example:
Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
System.out.printf("%s, %s, %s!", args.toArray());
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.
However, if the returned array's type is not important, simply using the toArray()
method is both easier and shorter.
For example:
Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
System.out.printf("%s, %s, %s!", args.toArray());
answered Jul 30 '17 at 9:19
KundaKunda
1715
1715
add a comment |
add a comment |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
Integer[] integers = stream.toArray(it->new Integer[it]);
add a comment |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
Integer[] integers = stream.toArray(it->new Integer[it]);
add a comment |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
Integer[] integers = stream.toArray(it->new Integer[it]);
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
Integer[] integers = stream.toArray(it->new Integer[it]);
edited Apr 15 '17 at 8:26
answered Apr 15 '17 at 8:20
Sagar Mal ShankhalaSagar Mal Shankhala
16125
16125
add a comment |
add a comment |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
int[] arr= stream.mapToInt(x->x.intValue()).toArray();
add a comment |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
int[] arr= stream.mapToInt(x->x.intValue()).toArray();
add a comment |
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();
answered Jun 8 '18 at 10:22
Raj NRaj N
878
878
add a comment |
add a comment |
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.
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);
add a comment |
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.
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);
add a comment |
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.
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);
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.
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);
edited Nov 27 '18 at 8:59
answered May 31 '18 at 8:54
raja emaniraja emani
174
174
add a comment |
add a comment |
protected by cassiomolin Mar 8 at 8:21
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
2
I'd suggest you to revert the rollback as the question was more complete and showed you had tried something.
– skiwi
Apr 15 '14 at 9:13
2
@skiwi Thanks! but i thought the attempted code does not really add more information to the question, and nobody has screamed "show us your attempt" yet =)
– user972946
Apr 15 '14 at 9:20
17
@skiwi: Although I usually shout at the do-my-homework-instead-of-me questions, this particular question seems to be clearer to me without any additional mess. Let's keep it tidy.
– Honza Zidek
Apr 16 '14 at 11:21