Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Wednesday, December 9, 2020

Java 8 Stream foreach Collect - Can not be done?

1. Overview

In this tutorial, We'll see whether can we use the forEach() method in the middle of stream operations such as stream().foreach().collect().

Another one can not we use the stream().forEach() and stream.collect() in one stream?

This is a common doubt for beginners when they start writing the programs in java 8 stream concepts.

First understand that forEach() and collect() methods are the terminal operations. That means theses are designed to produce the output of the stream and next end the stream. And also these two do not produce the stream result. So, we can not call further any stream methods.

We must be clear on Lambda Rules for usage.

But, we are trying to do with the calling forEach() in the middle of stream methods.

Let us see the simple examples.

Java 8 Stream foreach Collect - Can not be done?


2. Java 8 Stream forEach collect Example


Take a list with strings and try to do some filtering and then call forEach(). Finally, call collect method to store the final strings into a ArrayList.

package com.javaprogramto.java8.foreach;

import java.util.ArrayList;
import java.util.List;

public class Java8StreamForEachCollect {

	public static void main(String[] args) {

		List<String> list = new ArrayList<>();

		list.add("hello");
		list.add("world");
		list.add("welcome");
		list.add("to");
		list.add("javaprogramto.com");

		list.stream().filter(value -> value.contains("c")).forEach(value -> value + "-").collect();
	}
}

Now compile this code and see the error.

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	The method forEach(Consumer<? super String>) in the type Stream<String> is not applicable for the arguments ((<no type> value) -> {})
	Void methods cannot return a value

	at com.javaprogramto.java8.foreach.Java8StreamForEachCollect.main(Java8StreamForEachCollect.java:18)

It is saying forEach() method does not return any value but you are returning string value with "-" and on forEach() method calling collect() method.

Error: Void methods cannot return a value

3. Solve - Stream forEach collect


Actually, If we can see in the forEach method we are trying to do the change the value of string. So, we need to use another method map() rather than forEach() which will do modifying the values and returns a stream of new string values. And further we can collect the result into List and use forEach() method.

And also instead of collecting into list, on map() result we can call forEach() method directly.
package com.javaprogramto.java8.foreach;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Java8StreamForEachCollect {

	public static void main(String[] args) {

		// creating a list
		List<String> list = new ArrayList<>();

		// adding values to list
		list.add("hello");
		list.add("world");
		list.add("welcome");
		list.add("to");
		list.add("javaprogramto.com");

		// list.stream().filter(value -> value.contains("c")).forEach(value -> value +
		// "-").collect();

		// stream filter() + map() + collect() example
		List<String> newList = list.stream().filter(value -> value.contains("c"))
									.map(value -> value + "-")
									.collect(Collectors.toList());
		
		//printing the list
		System.out.println("Original List : "+list);
		System.out.println("New List Values : ");
		
		// print using forEach on list.
		newList.forEach(value -> System.out.println(value));
		
		// iterating stream using forEach()
		System.out.println("\niterating stream using forEach()");
		list.stream().filter(value -> value.contains("c"))
				.map(value -> value + "-")
				.forEach(str -> System.out.println(str));
	}
}

Output:
Original List : [hello, world, welcome, to, javaprogramto.com]
New List Values : 
welcome-
javaprogramto.com-

iterating stream using forEach()
welcome-
javaprogramto.com-

4. Conclusion


In this article, We've seen how to use the forEach() and collect() methods effectively in java 8 streams.


No comments:

Post a Comment

Please do not add any spam links in the comments section.