I’ve got a simple java pojo which looks like this:
class MyClass
{
public String getGroup();
public String getTitle();
}
Now what I want to do is to primarily sort a list of MyClass pojo by the values returned by the getTitle() method. Easy going though using my own comparator. However, what I want is that instances with the same value returned by getGroup() being followed by each other. Now what I did was something like
.. compare(MyClass c1, MyClass c2)
{
if (c1.getGroup().compareTo(c2.getGroup()) == 0)
{
return c1.getTitle().compareTo(c2.getTitle());
}
return c1.getGroup().compareTo(c2.getGroup());
}
However, the issue of this code is that it is no longer primarily sorted by the title because I do first compare the content of the groups, not the title, so a group starting with “B” would come before a group starting with “C” eventhough its title may come first.. what’s the proper way to primarily sort by title but make sure groups are “groupped” together as well?
Sample data:
MyClass 1 (group = "A", title="5")
MyClass 2 (group = "B", title="9")
MyClass 3 (group = "B", title="1")
Using my previous code would end up in
MyClass 1 (group = "A", title="5")
MyClass 3 (group = "B", title="1")
MyClass 2 (group = "B", title="9")
-> sort by group, then sort by title
But I want
MyClass 3 (group = "B", title="1")
MyClass 2 (group = "B", title="9")
MyClass 1 (group = "A", title="5")
-> sort by title but make sure each equal group follows each other that’s why still MyClass 1 with title “5” comes after MyClass 2 with title “9”…
Can’t be done with a Comparator. You need to run through the sorted titles, then for each unvisited title sort the corresponding groups. Here’s some sample code that sorts like the way you wanted.
}