【问题标题】:How to extract values from a list of class objects, remove the duplicates and sort alphabetically?如何从类对象列表中提取值,删除重复项并按字母顺序排序?
【发布时间】:2020-08-30 18:54:41
【问题描述】:
我在java中有一个类标签
public class Tag {
private int excerptID;
private String description;
}
我正在从 Tag 对象列表中提取描述 rawTags 到一个集合(我需要删除重复值):
Set<String> tags = rawTags.stream().map(Tag::getDescription).collect(Collectors.toSet());
但我也希望结果集(或唯一描述列表)按字母顺序排列。有没有办法直接将 TreeSet 与收集器一起使用,或者如何提取、删除重复项和按字母顺序排序的最简单方法是什么?
【问题讨论】:
标签:
java
duplicates
java-stream
treeset
collectors
【解决方案1】:
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);
}
【解决方案2】:
您可以使用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)));