问题描述
我在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)));