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

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 = rawTags.stream().map(Tag::getDescription).collect(Collectors.toSet());

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:

Set<String> tags = rawTags.stream() //or you can assign to TreeSet directly
    .map(Tag::getDescription)
    .collect(Collectors.toCollection(TreeSet::new));

and in case you wanted to pass custom comparator :

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