I have a class Tag in java
JavaScript
x
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):
JavaScript
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:
JavaScript
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 :
JavaScript
.collect(Collectors.toCollection(() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER)));