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

问题描述

我在Java中有一个类 Tag

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

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

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

,但我也想按字母顺序排列结果集(或唯一描述列表)。有没有一种方法可以直接将TreeSet与Collector一起使用,或者是最简单的方法来提取,删除重复项并按字母顺序排序?

解决方法

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);
    }
,

您可以使用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)));

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...