Stream converts a Java stream into an array

Posted by icez on Sun, 05 Sep 2021 10:05:20 +0200

The best way to convert a Java stream to an array is to use   Stream.toArray (IntFunction)   method.

We will convert a Java stream to an array in the following ways.

one   We will use   Stream.toArray (IntFunction)   Returns an array of the desired type.

two   use   Stream.toArray (IntFunction)   Method returns Object []  , Then change it to the desired data type.

three   For integer streams, we can use IntStream.toArray() to return int []. We can use the same method, LongStream.toArray()   Return long [] and DoubleStream.toArray(), return double [].

four   We can convert the stream to a list, and then convert the list to an array. To convert the stream into a list, we need to use collect(Collectors.toList()) on the stream to convert the list into an array. We can use the List.toArray method.

1. Use Stream.toArray (IntFunction)

The toArray (IntFunction) method uses the provided generator as an IntFunction to return an array containing this stream element. This method is the operation of the terminal.

A[] toArray(IntFunction<A[]> generator)

Parameters:   Pass the generator as an IntFunction that generates a new array of the required type and length.

return:   This method returns an array of stream elements.

Throw:   This method throws an ArrayStoreException if the runtime type of any element in this flow is not assignable to the runtime component type that generates the array.

Example 1:

In this example, we convert the character stream into an array of strings.

List<String> list = Arrays.asList("A", "B", "C", "D");
String[] strArray = list.stream().toArray(String[]::new);
for(String s : strArray) {
  System.out.println(s);
} 

The output is A B C D. In the above example, we instantiate IntFunction as a generator in the toArray method using a method reference.

Example of lambda expression.

String[] strArray = list.stream().toArray(size -> new String[size]);

Look at another example

public class StreamToStringArray {
  public static void main(String[] args) {
     List<String> list = Arrays.asList("Krishna", "Mahesh", "Kush");
     String[] strArray = list.stream()
    	 .filter(e -> e.startsWith("K"))
    	 .toArray(size -> new String[size]);
     for(String s : strArray) {
       System.out.println(s);
     }
  }
} 

output

Krishna
Kush 

Example 2:

In this example, we convert the integer stream to an array of integers.

public class StreamToIntegerArray {
  public static void main(String[] args) {
     List<Integer> list = Arrays.asList(10, 20, 30, 40);
     Integer[] intArray = list.stream()
    	 .map(e -> e * 2)
    	 .toArray(Integer[]::new);
     for(Integer i : intArray) {
       System.out.println(i);
     }
  }
} 

The output is 20 40 60 80.

In the above example, we used method references.

Now use the lambda expression.

List<Integer> list = Arrays.asList(10, 20, 30, 40);
Integer[] intArray = list.stream()
  .map(e -> e * 2)
  .toArray(size -> new Integer[size]); 

2. Use Stream.toArray()

  toArray ()   Method returns an Object array containing this stream element.

Object[] toArray()

This method is the operation of the terminal.

Example 1:  

In this example, we convert a string into an array of strings. We know that toArray() returns Object [], so in order to convert it in the data type we need, we can use the Arrays.copyOf method.

Object[] objArray = Stream.of("AA", "BB", "CC").toArray();
String[] stArray = Arrays.copyOf(objArray, objArray.length, String[].class);

for(String s : stArray) {
  System.out.println(s);
} 

The output is AA BB CC.

Example 2:  

In this example, we convert the integer stream to an array of integers.

Object[] objArray = Stream.of(10, 20, 30, 40).toArray();
Integer[] intArray = Arrays.copyOf(objArray, objArray.length, Integer[].class);

for(Integer i : intArray) {
  System.out.println(i);
} 

The output is 10 20 30 40.

3. Use IntStream.toArray()

IntStream is the stream of int valued elements. The IntStream.toArray() method converts an int value stream to an int array.

int[] toArray()

We can obtain the IntStream object in the following three ways

1.IntStream intStream = IntStream.of(1,2,3,4,5);

2.IntStream intStream = IntStream.rangeClosed(1, 5);

3.IntStream intStream = Stream.of(4,5,6,7,8).mapToInt(i -> i);

Now let's look at some examples of using the IntStream.toArray() method.

Example 1:

int[] intArray = IntStream.of(10, 20, 30, 40).toArray();
for(Integer i : intArray) {
  System.out.println(i);
} 

The output is 10 20 30 40.

Example 2:

int[] intArray = IntStream.rangeClosed(10, 15).toArray();
for(Integer i : intArray) {
  System.out.println(i);
} 

The output is 10 11 12 13 14 15.

Example 3:

int[] intArray = Stream.of(3,4,5,6).mapToInt(i -> i * 2).toArray();
for(Integer i : intArray) {
  System.out.println(i);
} 

The output is 6 8 10 12.

4. Use Collectors.toList()

We can convert the stream into a list, and then convert the list into an array. To convert a stream into a list, we need to use collect(Collectors.toList()) on the stream. To convert list to array, we can use the List.toArray method.

public class StreamToListToArray {
  public static void main(String[] args) {
	System.out.println("--- For String ---");
	String[] ar = Stream.of("Java", "Angular", "Spring")
		.collect(Collectors.toList())
		.toArray(new String[0]);
	
	for(String e : ar) {
	    System.out.println(e);	  
	}
	
	System.out.println("--- For Integer ---");
	Integer[] intArray = Stream.of(15, 20, 30)
		.map(e -> e * 2)
		.collect(Collectors.toList())
		.toArray(new Integer[0]);
	
        for(Integer i : intArray) {
            System.out.println(i);
        }	
  }
} 

output

--- For String ---
Java
Angular
Spring
--- For Integer ---
30
40
60 

reference resources:

https://www.concretepage.com/java/java-8/convert-java-stream-to-array

https://blog.csdn.net/qq_31635851/article/details/111145708

Topics: Java