首先感谢您的阅读!
我创建了一个自定义类CallLog
,其中包含logId
、logName
、logCompany
、...
这些 CallLog 存储在 TreeSet 中,并默认按 logPriority
和 logDateTime
排序。现在我需要打印按不同值排序的融洽关系。我使用 printByName()
等方法创建了抽象类 Rapport
,以便按其他值对 TreeSet 进行排序。
我不应该更改 CallLog 的 compareTo()
方法,因此我想知道如何使用 CallLog
的其他属性对 TreeSet 进行排序。
最佳答案
您无法更改现有 TreeSet
的排序,但可以使用自定义 Comparator
将值复制到以不同方式排序的另一个[临时]集合。 。事实上,您甚至不必创建新的集合,您只需在打印流式值时对它们进行排序即可:
例如:
public class Report {
private Set<CallLog> calls = // initialized somehow...
public void printByName() {
calls.stream()
.sorted(Comparator.comparing(CallLog::logName))
.forEach(System.out::println);
}
关于java - 如何对预排序 TreeSet 中对象的某些属性进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534657/