For example, after calling filter() you can still call the map() method on Stream.
// Converting product List into Set Set < Float > productPriceList = productsList.stream().filter(product -> product.getPrice() < 30000) .map(product -> product.getPrice()).collect(Collectors.toSet());
Once a terminal method like forEach() or collect() is called, you cannot call any other method of Stream or reuse the Stream.”
List<String> lines = Arrays.asList("java", "c", "python"); List<String> result = lines.stream() // convert list to stream .filter(line -> !"c".equals(line)) // we dont like c .collect(Collectors.toList()); // collect the output and convert streams to a List result.forEach(System.out::println);
The key difference between map() vs flatMap() in Java 8:
public class Main { public static void main(String[] args) { List<Integer> evens = Arrays.asList(2, 4, 6); List<Integer> odds = Arrays.asList(3, 5, 7); List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11); List<Integer> numbers = Stream.of(evens, odds, primes) .flatMap(list -> list.stream()) .collect(Collectors.toList()); System.out.println("flattend list: " + numbers); } } Output:
flattend list: [2, 4, 6, 3, 5, 7, 2, 3, 5, 7, 11]
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<String> listOfStrings = Arrays.asList("1", "2", "3", "4", "5"); List<Integer> listOfIntegers = listOfStrings.stream() .map(Integer::valueOf) .collect(Collectors.toList()); System.out.println(listOfIntegers); } } output: java python
1. Collections are used to store and group the data in a particular data structure like List, Set, or Map. Whereas Streams are used to perform complex data processing operations like filtering, matching, mapping, etc on stored data such as arrays, collections, or I/O resources. That means, collections are mainly about data and streams are mainly about operations on data.
2. You can add to or remove elements from collections. But, you can’t add to or remove elements from streams. Stream consumes a source, performs operations on it, and returns a result. They don’t modify even the source also.
3. The main specialty of Java 8 Streams is that you need not worry about iteration while using Streams. Streams perform iteration internally behind the scene for you (using the forEach() method). You just have to mention the operations to be performed on a source.
On the other hand, you have to do the iteration externally over collections using loops.
4. Streams are traversable only once. If you traverse the stream once, it is said to be consumed. To traverse it again, you have to get a new stream from the source again. But, collections can be traversed multiple times.