英文:
How to extract values from a list of class objects, remove the duplicates and sort alphabetically?
问题
我有一个在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与Collectors,或者最简单的方法是如何提取、去除重复和按字母顺序排序?
英文:
I have a class Tag in java
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):
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?
答案1
得分: 4
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);
}
英文:
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
得分: 3
你可以使用 Collectors.toCollection
并传递方法引用给 TreeSet
构造函数:
Set<String> tags = rawTags.stream() //或者你可以直接分配给TreeSet
.map(Tag::getDescription)
.collect(Collectors.toCollection(TreeSet::new));
如果你想传递自定义比较器:
.collect(Collectors.toCollection(() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER)));
英文:
You can use Collectors.toCollection
and pass method reference to TreeSet
constructor:
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 :
.collect(Collectors.toCollection(() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER)));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论