Skip to content
Advertisement

How to extract values from a list of class objects, remove the duplicates and sort alphabetically?

I have a class Tag in java

JavaScript

and I am extracting descriptions from a list of Tag objects rawTags to a set (I need to remove duplicate values):

JavaScript

but I also want to have the resulting set (or list of unique descriptions) alphabetically ordered. Is there a way how to use TreeSet directly with Collectors or what would be the easiest way how to extract, remove duplicates and order alphabetically?

Advertisement

Answer

You can use Collectors.toCollection and pass method reference to TreeSet constructor:

JavaScript

and in case you wanted to pass custom comparator :

JavaScript
Advertisement