1. Introduction
The collect() method in the Java Streams API is a versatile and powerful tool used to transform the elements of a stream into a different form, typically a collection like a List, Set, or a Map. It is one of the most flexible operations within the Stream API, enabling developers to accumulate elements from a stream into a container of their choice or perform mutable fold operations. This method is particularly useful for gathering results after performing operations such as filtering, mapping, or sorting on a stream.
Key Points
1. collect() is a terminal operation that transforms the output of a stream into a collection or other data structure.
2. It often uses predefined collectors from the Collectors utility class, including methods like toList(), toSet(), and toMap().
3. Custom collectors can be created to perform more complex aggregation operations.
2. Program Steps
1. Import necessary Java classes.
2. Create a stream of elements.
3. Apply transformations and collect the results.
4. Display the collected results.
3. Code Program
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamCollectExample {
public static void main(String[] args) {
// Step 2: Create a stream of elements
Stream<String> namesStream = Stream.of("John", "Jane", "Adam", "Alice", "Bob");
// Step 3: Collect results into a list
List<String> namesList = namesStream.collect(Collectors.toList());
// Additional collection types for demonstration
Set<String> namesSet = namesList.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toSet());
// Step 4: Display the results
System.out.println("Names List: " + namesList);
System.out.println("Names Set (starting with 'A'): " + namesSet);
}
}
Output:
Names List: [John, Jane, Adam, Alice, Bob]
Names Set (starting with 'A'): [Adam, Alice]
Explanation:
1. Stream Creation: A Stream of String objects is created from a hardcoded array. Streams provide a high-level abstraction for processing sequences of elements.
2. Collection into List: The stream elements are collected into a List using Collectors.toList(), which gathers all input elements and stores them in an ArrayList.
3. Filtering and Collecting into Set: An additional example demonstrates converting a list to a stream, applying a filter to retain only names that start with 'A', and collecting the results into a Set to eliminate duplicates and demonstrate different collection strategies.
4. Output: The results are printed to the console, showing how elements from the stream are first collected into a list and then into a set after filtering. This illustrates the versatility of the collect() method in collecting and transforming stream elements into various types of collections.
5. Use in Applications: The collect() method is crucial in real-world applications for data manipulation and aggregation tasks. It allows developers to gather processed data into common data structures, making it easier to integrate stream processing results into application logic.
Related Java 8 Source Code Examples:
Java Simple Lambda Expression Example
Java Lambda Expressions Multiple Statements
Java Lambda Expressions forEach Example
Java Lambda Expression with Multiple Parameters Example
Java Lambda Expression Runnable Example
Java Lambda Expression Comparator Example
Refactoring Factory Design Pattern with Lambdas
Refactoring Chain of Responsibility Pattern with Lambdas
Refactoring Observer Design Pattern with Lambdas
Refactoring Strategy Design Pattern with Lambdas
Iterate HashMap with forEach() + Lambda Expression Example
Iterate HashSet with forEach() + Lambda Expression Example
Iterate ArrayList with forEach() + Lambda Expression Example
Java method reference to a constructor example
Java method reference to static method example
Java method reference to an instance method of an object example
Java method reference to an instance method of an arbitrary object of a particular type
Java 8 - Create Stream Object from Arrays Example
Java 8 Creating a Stream from an Array
Java 8 - Create Stream Object from Collection, List, Set
Java 8 Stream - Sort List of String objects in Descending Order Example
Java 8 Stream - Sort List of String objects in Ascending Order Example
How to convert a Java 8 Stream to an Array?
Java 8 Stream - allMatch(),anyMatch() and noneMatch() Example
Java 8 Stream - Sort List of Objects by Multiple Fields
Java 8 Stream - Sort List of Custom Objects in Ascending and Descending Order
Java 8 - Stream filter(), forEach(), collect() and Collectors.toList() Example
Java Stream filter null values example
Java Stream filter map by values example
Java Stream filter map by keys example
Java 8 Collectors.counting() Example
Java 8 Collectors.averagingDouble() Example
Java 8 Collectors.toSet() Example
Java 8 Collectors.toList() Example
Java 8 Collectors.joining() example
Java 8 Stream multiple filter operations
Java 8 Stream filter map by keys
Java 8 Stream filter map by values
Java 8 Stream collect to list example
Java 8 Stream Collectors.counting() exmaple
Java 8 Collectors.collectingAndThen() example
Java 8 Collectors.toList() Example
Java 8 Collectors.minBy() and Collectors.maxBy() example
Java Stream filter() Example
Java Stream map() Example
Java Stream flatMap() Example
Java Stream distinct() Example
Java Stream limit() Example
Java Stream peek() Example
Java Stream anyMatch() Example
Java Stream allMatch() Example
Java Stream noneMatch() Example
Java Stream collect() Example
Java Stream count() Example
Java Stream findAny() Example
Java Stream findFirst() Example
Java Stream forEach() Example
Java Stream min() Example
Java Stream max() Example
Java Stream reduce() Example
Java Stream toArray() Example
Java Function Functional Interface Example
Java Supplier Functional Interface Example
Java Consumer Example
Java BiConsumer Example
Java BiFunction Example
Java Predicate Example
Java 8 LongConsumer Example
Java 8 IntConsumer Example
Java 8 DoubleConsumer Example
Java StringJoiner Example
Create Optional Class Object in Java - empty(), of(), ofNullable() Methods
Optional get() Method - Get Value from Optional Object in Java
Optional isPresent() Method Example
Optional orElse() Method Example
Optional orElseGet() Method Example
Optional orElseThrow() Method Example
Optional filter() and map() Method Examples
Java 8 program that counts the number of vowels and consonants in a given string
Java 8 program that reverses words of a given string
Java 8 - Copy List into Another List Example
Check Whether the Given Year is Leap Year or Not in Java
Java 8 forEach() Array Example
Java 8 forEach() Map Example
Java 8 forEach() Set Example
Java 8 forEach() List Example
Getting current date and time with Clock
Convert LocalDate to Date in Java
Convert LocalDateTime into Date in Java
Connvert java.util.Date to java.time.LocalDateTime Example
Convert java.util.Date to java.time.LocalDate Example
Duration Between Two LocalDate in Java
Java Convert ZonedDateTime to String Example
Convert String to ZonedDateTime in Java
Compare ZonedDateTime Objects in Java
How to Get Hour, Minute, Second from ZonedDateTime in Java
Convert ZonedDateTime to LocalTime Example
Convert ZonedDateTime to LocalDateTime in Java
Java ZonedDateTime now() and of() Method Example
Convert LocalDateTime to LocalTime in Java
Convert LocalDateTime to LocalDate in Java
Compare LocalDateTime Objects in Java
Java LocalDateTime - Get Hour, Minute and Second
How to Get Day Month and Year from LocalDateTime in Java
Java LocalDateTime now() Method Example
How to Get Current Date Time in Java
Convert LocalDate to String in Java
Convert String to LocalDate in Java
Java LocalDate isLeapYear() Method Example
How to Get Number of Days from Month and Year using LocalDate in Java
Compare Java LocalDate Objects Example
How to Add Days Weeks Months and Years to LocalDate in Java
How to get Day Month and Year from LocalDate in Java
Java LocalDate now() Method Example - Get Current Date and Specific Date
Convert LocalTime to String in Java
Convert String to LocalTime in Java
Java LocalTime isBefore() and isAfter() Method Example
How to Compare Time in Java
Java 8 - LocalTime getHour(), getMinute(), getSecond() and getNano() Example
Java LocalTime now() Method Example - Get Current Time and Specific Time
Java 8 Get Local Date Time in All Available Time Zones
How to get year, month, day, hours, minutes, seconds and milliseconds of LocalDateTime in Java 8?
How to get year, month, day, hours, minutes, seconds and milliseconds of Date in Java?
Difference between Two Dates in Java
Create LocalDateTime from LocalDate and LocalTime in Java
Java 8
Stream
Comments
Post a Comment