In this Java 8 example, we will take a look at how to iterate over an Array using Java 8 Stream and foreach method,
Code Example 1:1 | public static void main(String[] args) {
2 | int[] numbers = {1,2,3,4,5,6};
3 | Arrays.stream(numbers).forEach(System.out::println);
4 | }
Output:
1
2
3
4
5
6
As you see int array at the line number 2 and on line 3 we convert this array to stream using Arrays.stream(int[] arr) method and then use foreach over it and print the values out using System.out::println
Code Example 2:
public static void main(String[] args) {
String[] languages = {"Java","Python","Php","C#","Go"};
Arrays.stream(languages).forEach(System.out::println);
}
Output:
Java
Python
Php
C#
Go
Code Example 3:
public static void main(String[] args) {
double[] prices = {19.99, 29.99, 9.99, 49.99};
Arrays.stream(prices).forEach(price -> System.out.printf("$%.2f%n", price));
}
Output:
$19.99
$29.99
$9.99
$49.99
In this example, we have a double array of prices. We use Arrays.stream(double[] arr) to convert the array to a stream and then format the output using System.out.printf to display the prices in a currency format.
Code Example 4:
public static void main(String[] args) {
List fruits = Arrays.asList("Sunday", "Monday", "Tuesday", "Friday");
fruits.stream().forEach(fruit -> System.out.println("Day: " + fruit));
}
Output:
Day: Sunday
Day: Monday
Day: Tuesday
Day: Friday
Here, we have a List
Frequently Asked Questions (FAQ)
-
Q: What is the advantage of using Streams in Java 8?
A: Streams provide a functional approach to processing sequences of elements, allowing for more concise and readable code. They also support parallel processing, which can improve performance on large datasets.
-
Q: Can I use Streams with other data structures?
A: Yes, Streams can be created from various data structures, including Lists, Sets, and Arrays, making them versatile for different use cases.
-
Q: How do I filter elements in a Stream?
A: You can use the filter method to filter elements based on a predicate. For example, stream.filter(n -> n > 10) will return a stream of elements greater than 10.
-
Q: What is the difference between map and flatMap?
A: The map method transforms each element in the stream, while flatMap is used to flatten nested structures, combining multiple elements into a single stream.
-
Q: Can I modify the original array while using Streams?
A: No, Streams are designed to be non-mutating. If you need to modify the original data, you should do so before creating the stream.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!