I want to ask a question about sorting in Java, to be precise i need to sort a list of tuples (that are defined as a custom class) but that are linked like a tree to each other.
Basically this is a list of document ids that express the relation parent-child, and are organized as sets (possibly unordered). The tuples are already filtered to have unique left / right elements, so that the tree has unique links between documents (they are not allowed to have multiple leafs).
Using example data, i have this kind of list: [(1,2), (3,4), (0,1), (2,3)], this represents the following tree:
0
|_ 1
|_ 2
|_ 3
|_ 4
Hence i need the list to be ordered as follow: [(0,1), (1,2), (2,3), (3,4)].
I also add that it's possible that the parent document id is greater than the child one, so a simple sorting based on which id is greater is not possible.
I tried using the .sorted() method of the Stream class, after making the custom class comparable and adding the following code:
@Override
public int compareTo(DocumentIdVersionsStack o) {
if (parentDocumentId == o.getChildDocumentId()) return 1;
if (childDocumentId == o.getParentDocumentId()) return -1;
return 0;
}
Basically telling it to invert the order if the current one is child of the other tuple and vice versa, but the list is still not what i expect it to be.
Any idea on how to do this using streams? I didn't want to use complex sortings methods that require recursion, just to keep the code cleaner, but if it can't be done otherwise i'll check that.
Thank you!
EDIT: I'll add a couple of informations:
- The tuples are already contiguous, there won't be 'holes' of missing ids
- The recursion (last id = first id) is again taken care before passing the tuples to the sorting method
- There will be a tuple with the left value not found in any of the right values -> this will be the first element after the sort
- There will be a tuple with the right value not found in any of the left values -> this will be the last element after sort
- All left and right values are unique, they are just linked as explained before (left1 = right2 and so on)