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

Tags: , , , ,

I have a class Tag in java

public class Tag {
    private int excerptID;
    private String description;

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

Set<String> tags =;

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?


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

Set<String> tags = //or you can assign to TreeSet directly

and in case you wanted to pass custom comparator :

.collect(Collectors.toCollection(() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER)));

Source: stackoverflow