- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Array To Stream in Java
With Java 8, Arrays class has a stream() methods to generate a Stream using the passed array as its source.
Description
The java.util.Arrays.stream() method returns a sequential Stream with the specified array as its source. −
Arrays.stream(array)
Declaration
Following is the declaration for java.util.Arrays.stream() method
public static <T> Stream<T> stream(T[] array)
Type Parameter
T − This is the type of the array elements.
Parameter
array − This is the source array to be used.
Return Value
This method returns a stream for the array.
Example
The following example shows the usage of java.util.Arrays.stream() method.
import java.util.Arrays; public class Tester { public static void main(String args[]) { int data[] = { 1, 2, 3, 4, 5 }; //iterative way to compute sum and average of an array int sum = 0; for(int i = 0; i< data.length; i++) { sum+= data[i]; } System.out.println("Sum : " + sum); System.out.println("Average : " + sum/data.length); //declarative way to compute sum and average of an array sum = Arrays.stream(data).sum(); System.out.println("Sum : " + sum); System.out.println("Average : " + sum/data.length); } }
Output
Compile and Run the file to verify the result.
Sum : 15 Average : 3 Sum : 15 Average : 3
Advertisements