Mon. Apr 22nd, 2024

Search for this lovely gem that came in Java 8, and you will find plenty of articles on how to create your own Collector, and calling Streams.collect() with a collector to gather the data into a collection. Neither of these was the problem I was trying to solve.  I wanted to know how to add this object to my code in order to make a collection.  The ability to pass the various types of Collectors and make use of them really makes things far more powerful.  So let’s talk about what you need.

Collector object

Collector<T, A, R>	collector;

To begin import in the Collector interface.  Then the parameter type or member variable you need is the Collector<T, A, R>.  This is the Object you need to keep.

Adding to the Collection

A supplier = collector.supplier().get();
collector.accumulator().accept(this.supplier, (T) data);

First thing get a reference to the supplier.  Save this because you will need this later to get the collection when you are finished.

Now access the accumulator to call the accept() method.  The first parameter is the supplier, and the second parameter is the data your adding to the Collection.  It should be of type T, cast if necessary.

Getting your final results

R collection = collector.finisher().apply(supplier);

Once you have added all of your data to your collector.  Your final step is to get your Collection from it.  This is accomplished by calling apply on the finisher passing in the supplier. This will return to you the type of your collection R.

Hope this helps you!

By Jeffery Miller

I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.