Java Stream Iterate Example - onlyxcodes

Saturday, 25 March 2023

Java Stream Iterate Example

Java 8 introduces a brand-new package called java.util.stream. The processing of collections of items is done via the Stream API. A stream is a collection of objects that can support several operations and be pipelined to create the desired outcome.


The Java 8 stream has the characteristics listed below:


A stream accepts input from Collections, Arrays, or I/O ways; it is not a data structure.


Streams just deliver the results of the pipelined operations; they don't alter the underlying data structure in any way.


Different intermediate operations can be pipelined together since each intermediate operation is run lazily and produces a stream as an output. The stream is marked by terminal operations, which also return the outcome.


In this tutorial, we'll go over the flat map and stream collector capabilities as well as the Java stream Iterate example.


java stream iterate example

Java Stream Iterate Example

The Java Stream Iterate method enables you to build a Stream object that iterates through a list of elements.


It requires two parameters: the starting value of the stream and an UnaryOperator that specifies how to produce the subsequent value in the sequence according to the previous one.


Here is an example of how to build an integer stream from 0 to 9 or n times using the Stream Iterate method:


The UnaryOperator in this example is defined as n -> n + 1, which means that each number after the initial value will be one greater than the previous value. The stream can only have 10 elements after calling the limit(10) method.


package com.onlyxcodes;

import java.util.stream.Stream;

public class Test 
{
	public static void main(String args[])
	{
		Stream<Integer> stream = Stream.iterate(0, n -> n + 1).limit(10);
		stream.forEach(System.out::println);	
	}
}

Output:


0
1
2
3
4
5
6
7
8
9

Java Stream Iterate List Example

In this example, we first use the Arrays.asList() method to create a list of strings called countries.


The forEach() method is then used to traverse through the list using a stream and print each country to the console.


In order to define what action should be taken on each element of the stream, in this case printing it to the console, use the lambda expression country -> System.out.println(country).


package com.onlyxcodes;

import java.util.Arrays;
import java.util.List;

public class Test
{
	public static void main(String args[])
	{
		List<String> countries = Arrays.asList("usa", "canada", "australia", "uk");

        // Using streams to iterate through the list of countries
        countries.stream().forEach(country -> System.out.println(country));
	}
}

Output:


usa
canada
australia
uk

Java Stream Collect() Method Example

Consider the case when you have an integer list and you wish to make a new list that only contains the even values in the original list:


package com.onlyxcodes;

import java.util.Arrays;
import java.util.List;

import java.util.stream.Collectors;


public class Test
{
	public static void main(String args[])
	{
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

		List<Integer> evenNumbers = numbers.stream()
		                                   .filter(n -> n % 2 == 0)
		                                   .collect(Collectors.toList());

		System.out.println(evenNumbers);
		
	}
}

Output:


[2, 4, 6, 8, 10]

In the code above, we first use the Arrays.asList method to assemble a list of integers.


The stream method is then used on this list to produce an integer stream.


The next step is to remove the odd numbers from the stream using the filter method.


A lambda expression is used as the filter method's argument. The lambda expression n -> n% 2 == 0 in this situation determines whether the supplied number n is even. The number is kept in the stream if the condition returns true; else, it is filtered out.


The filtered integers are then collected into a new list using the Collectors.toList() method using the collect() method. When constructing collectors, the Collectors class has a number of static factory methods that can be used with the collect() method.


The filtered even numbers are created in a new List object by the Collectors.toList() method, which we then add to the evenNumbers variable. The System.out.println statement is then used to print the contents of this list.


Java Stream Iterate Until Condition Example

Here is an example of how to iterate using Java Stream until till a condition is satisfied:


Consider the situation where you have a list of integers and you want to identify the first even number that is bigger than 10. Once the condition is satisfied, you can iterate across the list using a stream.


package com.onlyxcodes;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;


public class Test
{
	public static void main(String args[])
	{
		List<Integer> numbers = Arrays.asList(2, 7, 12, 15, 18, 20, 25);

		Optional<Integer> result = numbers.stream()
		        .filter(n -> n > 10 && n % 2 == 0) // filter for even numbers greater than 10
		        .findFirst(); // find the first number that meets the condition

		if (result.isPresent()) 
		{
		    System.out.println("First even number greater than 10 is = " + result.get());
		} 
		else 
		{
		    System.out.println("No even number greater than 10 found.");
		}

		
	}
}

Output:


First even number greater than 10 is = 12

In the code above, we first use the Arrays.asList method to craft a list of integers.


The stream's elements that don't fit the criteria are filtered out using the filter() method. We only want even numbers higher than 10 in this situation.


The return value of the findFirst() method is either an empty Optional object or an Optional object that contains the first element of the stream that matches the condition.


Lastly, we use the isPresent() method of the Optional class to determine whether a result is present. If so, we use the get() method to print out the value of the first even number larger than 10. If not, a message indicating that no element matches the requirement is printed.


Java Stream flatmap() Method Example

A Stream of collections can be flattened into a Stream of objects using the Stream flatMap() method. All of the collections in the original Stream's objects are merged.


The flatMap() action flattens the elements of the Stream into a new Stream after applying a one-to-many conversion to the Stream's components.


Assume the scenario where you wish to make a new list of all the terms in a list of strings that represent sentences. You can flatten the list of sentences into a stream of words using the flatMap() method, then compile the words into a new list.


package com.onlyxcodes;

import java.util.Arrays;
import java.util.List;

import java.util.stream.Collectors;

public class Test
{
	public static void main(String args[])
	{
        List<String> sentences = Arrays.asList(
                "new york is state of usa country",
                "auckland is state of new zealand country",
                "java stream flatMap example"
        );

        List<String> words = sentences.stream()
                .flatMap(sentence -> Arrays.stream(sentence.split(" ")))
                .collect(Collectors.toList());

        System.out.println(words);

	}
}

In the above example, we begin with a list of three sentences that are saved in the sentences list.


We separate each sentence into its component words using the split() function, and then we build a list using the Arrays.asList() method and a stream of words using the Arrays.stream() method.


Then, we flatten the word stream into a single stream using the flatMap() method so that we can collect it using the Collectors.toList() method. A new list of all the words from the original sentences is the final result.


Lastly, we use the System.out.println() method to print the updated list. Input will result in:


Output:


As you can see, we only needed a few lines of code to convert a list of phrases into a list of words using the flatMap() method.


 [new, york, is, state, of, usa, country, auckland, is, state, of, new, zealand, country, java, stream, flatMap, example]

Read Also:

What does double mean in Java

How to Remove a Character from a String in Java

How do you define a method in Java?

What do the replaceAll () do in Java?

Can I use LeetCode for Java?

How to Get the Length of a String in Java

How to make lists of lists in Java?

How to print each word in new line in Java

Why do we use :: (double colon) in Java

What is the Difference Between NoClassDefFoundError and ClassNotFoundException in Java

How to Replace a Character in a String in Java without using the Replace Method

What are Variable Arguments in Java

Context Switching in Java Thread Example

What Are the 4 types of loops in Java

How to Run Package Program in Java using Command Prompt

What is final class and method in Java

What is Encapsulation in Java with Realtime Example

3 Ways to Create Thread in Java

Java Code to Send Email with Attachment

How to Produce and Consume Restful Webservice in Java

No comments:

Post a Comment

Post Bottom Ad