【问题标题】:How can I sort on certain properties of an object in a pre-sorted TreeSet?如何对预先排序的 TreeSet 中对象的某些属性进行排序?
【发布时间】:2016-11-10 18:32:00
【问题描述】:

首先感谢您的阅读!

我用logIdlogNamelogCompany、...创建了一个自定义类CallLog 这些 CallLogs 存储在 TreeSet 中,默认按 logPrioritylogDateTime 排序。现在我需要打印按不同值排序的关系。我已经创建了abstract class Rapport 使用printByName() 之类的方法来按其他值对我的TreeSet 进行排序。

我不应该更改 CallLog 的 compareTo() 方法,所以我想知道如何使用 CallLog 的其他属性对 TreeSet 进行排序。

【问题讨论】:

  • 您无法对TreeSet 进行排序。它是自排序的,因此如果您打算更改排序,请使用 List 和众多排序列表的方法之一。

标签: java sorting compare treeset


【解决方案1】:

您无法更改现有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);
}

【讨论】:

    猜你喜欢
    • 2011-08-13
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 2012-04-26
    • 1970-01-01
    相关资源
    最近更新 更多