Jim Vekemans Jim Vekemans - 23 days ago 7
Java Question

How can I sort on certain properties of an object in a pre-sorted TreeSet?

First of all, thanks for reading!

I have created a custom class

CallLog
with
logId
,
logName
,
logCompany
, ...
These CallLogs are stored within a TreeSet and sorted by
logPriority
and
logDateTime
by default. Now I need to print rapports that are sorted by different values. I've created
abstract class Rapport
with methods like
printByName()
to sort my TreeSet by other values as well.

I'm not supposed to alter the
compareTo()
method of CallLog so I would like to know how to sort my TreeSet using other properties of the
CallLog
.

Answer

You can't change the sorting of an existing TreeSet, but you can copy your values to another [temporary] collection sorted differently by using a custom Comparator. In fact, you don't even have to create a new collection, you could just sort the streamed values as you print them: E.g.:

public class Report {
    private Set<CallLog> calls = // initialized somehow...

    public void printByName() {
        calls.stream()
             .sorted(Comparator.comparing(CallLog::logName))
             .forEach(System.out::println);
}
Comments