Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

"Key, Name"

and I want to convert that line into a String array, separating each value by the comma (,), however, I also want to trim every field before returning the final array, so I did the following:

Arrays.stream(line.split(",")).map(String::trim).toArray(); 

However, this returns an Object[] array rather than a String[] array. Upon further inspection, I can confirm that the contents are actually String instances, but the array itself is of Object elements. Let me illustrate this, this is what the debugger says of the returned object:

Object[]:     0 = (String) "Key"     1 = (String) "Name" 

As far as I can tell, the problem is in the return type of the map call, but how can I make it return a String[] array?

like image 507
arielnmz Avatar asked Dec 01 '16 03:12

arielnmz


People also ask

Can you convert Stream to an array?

In Java 8, we can use . toArray() to convert a Stream into an Array.

Which method in Stream can be used to create an array from the Stream?

The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.

How do you create an array of streams in Java?

Syntax : public static <T> Stream<T> getStream(T[] arr) { return Arrays. stream(arr); } where, T represents generic type. Example 1 : Arrays.


1 Answers

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<String[]>() {         @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

like image 143
Mritunjay Avatar answered Sep 28 '22 03:09

Mritunjay