Using Collectors
Collectors in Java are a very powerful tool when you need to extract certain data points, descriptions, or elements from large data structures. They offer a very understandable way of describing what you want to do with a stream of elements, without needing to write complex logic.
There are a number of helpful default implementations of the Collector
interface that you can start using easily. Most of these collectors will not allow null values; that is, if they find a null value in your stream, they will throw a NullPointerException
. Before using a collector to reduce your elements in any of these containers, you should take care to handle null elements in the stream.
The following is an introduction to all default Collectors:
toCollection
: This generic collector will allow you to wrap your elements in any known class implementing theCollection
interface; examples includeArrayList
,HashSet
,LinkedList
,TreeSet
, and others:List.of("one", "...