Sorting objects within a Set by a String value that all objects contain(按所有对象包含的字符串值对 Set 中的对象进行排序)
问题描述
好的,这是一个棘手的问题.我有一个集合列表.我想按顺序对集合中的对象进行排序.
Ok this is a tricky one. I have a list of Sets. I would like to sort the objects in the Sets in an order.
将每个集合想象成代表学校的一个班级.每个集合都包含人员对象.一个人对象持有一个字符串值作为名称.我想在循环并写出之前按名称排列 Set 中的 Persons.
Imagine each set as repressenting a class in a school. Each set contains person objects. A person object holds a String value for name. I'd like to arrange the Persons in the Set by name before I loop through and write them out.
有没有办法使用 Collections.sort();
或类似的东西来实现这一点?
Is there anywahy to use Collections.sort();
or something similar to achieve this?
for (Set<Person> s : listOfAllChildren) {
for (Person p : s) {
if(p.getClass().equalsIgnoreCase("Jones")){
System.out.println(p.getName());
}
else if...//carry on through other classes
}
}
我知道一个班有 2 个以上的孩子可能有相同的名字,但请忽略这个
推荐答案
一个 Set
没有 ordering 的概念,因为它是一个集合.
A Set
has no notion of ordering because, well, it's a set.
TreeSet
类实现的SortedSet
接口可以使用.只需向构造函数提供适当的 Comparator
,或让您的 Person
类实现 Comparable
.
There is a SortedSet
interface implemented by TreeSet
class that you can use. Simply provide an appropriate Comparator
to the constructor, or let your Person
class implements Comparable
.
这篇关于按所有对象包含的字符串值对 Set 中的对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按所有对象包含的字符串值对 Set 中的对象进行排序


- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01