Hello guys, you may know that Java 8 brought Stream API which supports a lot of functional programming operations like filter, map, flatMap, reduce, and collect. In this article, you will learn about the collect() method. The collect() method of Stream class can be used to accumulate elements of any Stream into a Collection. In Java 8, you will often write code that converts a Collection like a List or Set to Stream and then applies some logic using functional programming methods like the filter, map, flatMap and then converts the result back to the Collection like a List, Set, Map, or ConcurrentMap in Java.
In this last part, the collect() method of Stream helps. It allows you to accumulate the result into a choice for containers you want like a list, set, or map.
Programmers often confuse that the collect() method belongs to the Collector class but that's not true. It is defined in Stream class and that's why you can call it on Stream after doing any filtering or mapping. It accepts a Collector to accumulate elements of Stream into a specified Collection.
The Collector class provides different methods like toList(), toSet(), toMap(), and toConcurrentMap() to collect the result of Stream into List, Set, Map, and ConcurrentMap in Java.
It also provides a special toCollection() method which can be used to collect Stream elements into a specified Collection like ArrayList, Vector, LinkedList, or HashSet.
It's also a terminal operation which means after calling this method on Stream, you cannot call any other method on Stream.
Btw, if you are new to Java or Java 8 world then I suggest you first join a comprehensive course like The Complete Java MasterClass instead of learning in bits and pieces. The course provides a more structured learning material that will teach you all Java fundamentals in a quick time. Once you understand them you can explore the topic you like by following blog posts and articles.
The list returned by the collect method will have all the String which starts with "J" in the same order they appear in the original list because both Stream and List keep elements in order. This is an important detail which you should know because you often need to process and collect elements in order.
If you want to learn more about ordered and unordered collections I suggest you join Java Fundamentals: Collections course by Richard Warburton on Pluralsight. It's a specialized course on the Java Collection framework which is very important for any Java developer.
Programmers often confuse that the collect() method belongs to the Collector class but that's not true. It is defined in Stream class and that's why you can call it on Stream after doing any filtering or mapping. It accepts a Collector to accumulate elements of Stream into a specified Collection.
The Collector class provides different methods like toList(), toSet(), toMap(), and toConcurrentMap() to collect the result of Stream into List, Set, Map, and ConcurrentMap in Java.
It also provides a special toCollection() method which can be used to collect Stream elements into a specified Collection like ArrayList, Vector, LinkedList, or HashSet.
It's also a terminal operation which means after calling this method on Stream, you cannot call any other method on Stream.
Btw, if you are new to Java or Java 8 world then I suggest you first join a comprehensive course like The Complete Java MasterClass instead of learning in bits and pieces. The course provides a more structured learning material that will teach you all Java fundamentals in a quick time. Once you understand them you can explore the topic you like by following blog posts and articles.
Java 8 Stream.collect() Examples
In this article, we'll see a couple of examples of Stream's collect() method to collect the result of stream processing into a List, Set, and Map in Java. In other words, you can also say we'll convert a given Stream into List, Set, and Map in Java1. Stream to List using collect()
This is the first example of using the Stream.collect() method where we will collect the result of the stream pipeline in a List. You can collect the result of a Stream processing pipeline in a list by using the Collectors.toList() method. Just pass the Collectors.toList() to collect() method as shown below:List<String> listOfStringStartsWithJ
= listOfString
.stream()
.filter( s -> s.startsWith("J"))
.collect(Collectors.toList());
The list returned by the collect method will have all the String which starts with "J" in the same order they appear in the original list because both Stream and List keep elements in order. This is an important detail which you should know because you often need to process and collect elements in order.
If you want to learn more about ordered and unordered collections I suggest you join Java Fundamentals: Collections course by Richard Warburton on Pluralsight. It's a specialized course on the Java Collection framework which is very important for any Java developer.
2. Stream to Set using Collector.toSet() method
This is the second example of the collect() method of Stream class where we will collect the result of the Stream pipeline into a Set. You can use Collectors.toSet() method along with collect() to accumulate elements of a Stream into a Set.Since Set doesn't provide ordering and doesn't allow duplicate, any duplicate from Stream will be discarded and the order of elements will be lost.
Here is an example to convert Stream to Set using collect() and Collectors in Java 8:
The set of String in this example contains all the String which starts with the letter C like C and C++. The order will be lost and any duplicate will be removed.
Here is an example to convert Stream to Set using collect() and Collectors in Java 8:
The set of String in this example contains all the String which starts with the letter C like C and C++. The order will be lost and any duplicate will be removed.
Though, if you are new to functional programming in Java, I highly recommend you check out the Learn Java Functional Programming with Lambdas and Stream course by Ranga Karnam on Udemy. It's a hands-on course to learn all stream and lambda concepts.
For example, if you have a Stream of String then you can create a Map where the key is String itself and the value is their length, as shown in the following example:
The Function.identity() used here denotes that the same object is used as a key. Though you need to be a little bit careful since Map doesn't allow duplicate keys if your Stream contains duplicate elements then this conversion will fail.
In that case, you need to use another overloaded toMap() method also accepts an argument to resolve conflict in case of duplicate keys. Also, toMap() doesn't provide any guarantee on what kind of Map is returned. This is another important detail you should remember.
If you want to learn more about dealing with Collections and Stream I suggest you take a look at another Pluralsight gem, From Collections to Streams in Java 8 Using Lambda Expressions course.
There is also a toCollection() method in the Collectors class that allows you to convert Stream to any collection. In the following example, we will learn how to collect Stream elements into an ArrayList.
Since ArrayList is a list, it provides an ordering guarantee, hence all the elements in the ArrayList will be in the same order they appear in the original List and Stream.
If you find Javadoc boring then you can also join this best Java course, one of the most comprehensive Java courses on Udemy.
That's all about how to use the collect() method of Stream class in Java 8. Along with collect(), you can use the Collectors method to convert Stream to List, Set, Map, or any other Collection of your choice. Just explore the Collectors Javadoc to learn more about those methods.
Related Java 8 Tutorials
If you are interested in learning more about the new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
Thanks for reading this article so far. If you like this Java 8 Stream tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.
P. S. - If you love to learn from free courses, here is a collection of free online courses to learn Java 8 and Java 9 features on freeCodeCamp.
3. Stream to Map using toMap()
You can create a Map from elements of Stream using collect() and Collectors.toMap() method. Since a Map like HashMap stores two objects i.e. key and value and Stream contains just one element, you need to provide the logic to extract the key and value objects from the Stream element.For example, if you have a Stream of String then you can create a Map where the key is String itself and the value is their length, as shown in the following example:
Map<String, Integer> stringToLength
= listOfString
.stream()
.collect(
Collectors.toMap(Function.identity(), String::length));
The Function.identity() used here denotes that the same object is used as a key. Though you need to be a little bit careful since Map doesn't allow duplicate keys if your Stream contains duplicate elements then this conversion will fail.
In that case, you need to use another overloaded toMap() method also accepts an argument to resolve conflict in case of duplicate keys. Also, toMap() doesn't provide any guarantee on what kind of Map is returned. This is another important detail you should remember.
If you want to learn more about dealing with Collections and Stream I suggest you take a look at another Pluralsight gem, From Collections to Streams in Java 8 Using Lambda Expressions course.
4. Stream to Collection using Collectors.toCollection()
You can also collect or accumulate the result of Stream processing into a Collection of your choices like ArrayList, HashSet, or LinkedList.There is also a toCollection() method in the Collectors class that allows you to convert Stream to any collection. In the following example, we will learn how to collect Stream elements into an ArrayList.
ArrayList<String> stringWithLengthGreaterThanTwo
= listOfString
.stream()
.filter( s -> s.length() > 2)
.collect(Collectors.toCollection(ArrayList::new));
Since ArrayList is a list, it provides an ordering guarantee, hence all the elements in the ArrayList will be in the same order they appear in the original List and Stream.
If you find Javadoc boring then you can also join this best Java course, one of the most comprehensive Java courses on Udemy.
Java Program to Use Stream.collect() method
Here is our complete Java program to demonstrate the use of the collect() method of Stream class to convert Stream into different Collection classes in Java, like List, Set, Map, and Collection itself.import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; public class Code { public static void main(String[] args) { List<String> listOfString = Arrays.asList("Java", "C", "C++", "Go", "JavaScript", "Python", "Scala"); System.out.println("input list of String: " + listOfString); // Example 1 - converting Stream to List using collect() method List<String> listOfStringStartsWithJ = listOfString.stream() .filter(s -> s.startsWith("J")) .collect(Collectors.toList()); System.out.println("list of String starts with letter J: " + listOfStringStartsWithJ); // Example 2 - converting Stream to Set Set<String> setOfStringStartsWithC = listOfString.stream() .filter(s -> s.startsWith("C")) .collect(Collectors.toSet()); System.out.println("set of String starts with letter C: " + setOfStringStartsWithC); // Example 3 - converting Stream to Map Map<String, Integer> stringToLength = listOfString.stream() .collect(Collectors .toMap(Function.identity(), String::length)); System.out.println("map of string and their length: " + stringToLength); // Example - Converting Stream to Collection e.g. ArrayList ArrayList<String> stringWithLengthGreaterThanTwo = listOfString.stream() .filter(s -> s.length() > 2) .collect(Collectors. toCollection(ArrayList::new)); System.out.println("collection of String with length greather than 2: " + stringWithLengthGreaterThanTwo); } } Output input list of String: [Java, C, C++, Go, JavaScript, Python, Scala] list of String starts with letter J: [Java, JavaScript] set of String starts with letter C: [C++, C] map of string and their length: {Java=4, C++=3, C=1, Scala=5, JavaScript=10, Go=2, Python=6} collection of String with length greather than 2: [Java, C++, JavaScript, Python, Scala]
That's all about how to use the collect() method of Stream class in Java 8. Along with collect(), you can use the Collectors method to convert Stream to List, Set, Map, or any other Collection of your choice. Just explore the Collectors Javadoc to learn more about those methods.
Related Java 8 Tutorials
If you are interested in learning more about the new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
- How to join String in Java 8 (example)
- How to use filter() method in Java 8 (tutorial)
- 5 Free Courses to learn Java 8 and 9 (courses)
- How to use Stream class in Java 8 (tutorial)
- 10 Advanced Core Java courses for Programmers (courses)
- How to use forEach() method in Java 8 (example)
- 20 Examples of Date and Time in Java 8 (tutorial)
- 5 Books to Learn Java 8 from Scratch (books)
- How to convert List to Map in Java 8 (solution)
- My favorite free courses to learn Java in-depth (courses)
- Best Courses to learn Java Programming for Beginners (best courses)
- Difference between abstract class and interface in Java 8? (answer)
- 10 Free Courses for Experienced Java Programmers (courses)
- How to use peek() method in Java 8 (example)
- best Courses to learn Data structure and Algorithms (best courses)
- How to sort the may by values in Java 8? (example)
- How to format/parse the date with LocalDateTime in Java 8? (tutorial)
- Top 5 Java 8 Tutorials for Programmers (courses)
P. S. - If you love to learn from free courses, here is a collection of free online courses to learn Java 8 and Java 9 features on freeCodeCamp.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.