如何从 class 个对象列表中提取值、删除重复项并按字母顺序排序?

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

我在java

中有一个class标签
public class Tag {
    private int excerptID;
    private String description;
    }

我正在从 Tag 对象列表 rawTags 中提取描述到一个集合(我需要删除重复值):

Set<String> tags = rawTags.stream().map(Tag::getDescription).collect(Collectors.toSet());

但我还希望结果集(或唯一描述列表)按字母顺序排列。有没有一种方法可以直接将 TreeSet 与 Collectors 一起使用,或者提取、删除重复项和按字母顺序排序的最简单方法是什么?

您可以使用 Collectors.toCollection 并将方法引用传递给 TreeSet 构造函数:

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

如果您想通过自定义比较器:

.collect(Collectors.toCollection(() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER)));
public static void main(String[] args) {
        Tag tag1 = new Tag(1,"9a");
        Tag tag2 = new Tag(2,"32");
        Tag tag3 = new Tag(3,"4c");
        Tag tag4 = new Tag(4,"1d");

        List<Tag> rawTags = new ArrayList<>();
        rawTags.add(tag1);rawTags.add(tag2);rawTags.add(tag3);rawTags.add(tag4);
        Set<String> tags = rawTags.stream().map(Tag::getDescription).collect(Collectors.toCollection(TreeSet::new));
        System.out.print(tags);
    }