Question

I need to create a comparator to sort arraylist with a couple of xpaths and priority indicators... First criterium is to sort xpaths in descending order, second criterium is: if paths are the same, path with higher priority will be first Here is the list: xpath priority

Before comparison:

/HTML[1]/BODY[1]/P[2]            5
/HTML[1]/BODY[1]/P[1]/text()[1]  2 
/HTML[1]/BODY[1]/P[2]/text()[3]  2
/HTML[1]/BODY[1]/P[3]/text()[1]  4
/HTML[1]/BODY[1]/P[2]/text()[1]  1
/HTML[1]/BODY[1]/P[4]/text()[1]  3
/HTML[1]/BODY[1]/P[1]/text()[1]  3

After comparison:

/HTML[1]/BODY[1]/P[4]/text()[1]  3
/HTML[1]/BODY[1]/P[3]/text()[1]  4
/HTML[1]/BODY[1]/P[2]            5
/HTML[1]/BODY[1]/P[2]/text()[3]  2
/HTML[1]/BODY[1]/P[2]/text()[1]  1
/HTML[1]/BODY[1]/P[1]/text()[1]  3
/HTML[1]/BODY[1]/P[1]/text()[1]  2

This is what I have so far, but it's not working properly :/

Collections.sort(mods, new Comparator<TextModification>() {
@Override
public int compare(TextModification  mod1, TextModification  mod2)
{

//Comapre paths
int pathComp =  mod2.getPath().compareTo(mod1.getPath());

//If mod2.path is "less" than mod1.path
if(pathComp < 0){
  if(mod1.getPath().startsWith(mod2.getPath())){
    return 1;
  }
}

//Return comparison
if(pathComp != 0){
  return pathComp;
}

//If paths are the same, sort by priority indicator
return mod2.getPriority() > mod1.getPriority() ? 1 : -1;
}
});

Thanks in advance

Was it helpful?

Solution

You want to sort in reverse path order, except when one path extends another. A simple work around is to add a high-ascii valued character ("z" is convenient) to the end of the path before comparing:

Collections.sort(mods, new Comparator<TextModification>() {
    @Override
    public int compare(TextModification mod1, TextModification mod2) {
        int pathComp = (mod2.getPath() + "z").compareTo(mod1.getPath() + "z");
        return pathComp == 0 ? mod2.getPriority() - mod1.getPriority() : pathComp;
    }
});

Note also the simplification of the code using a ternary operator and a priority difference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top