3

Im just learning Collections and I have a task. Some organization want to create a cataloge of departments. Codes of departments are array of Strings:

    “K1\SK1”
    “K1\SK2”
    “K1\SK1\SSK1”
    “K1\SK1\SSK2”
    “K2”
    “K2\SK1\SSK1”
    “K2\SK1\SSK2” 

I need to sort codes of departments descendign and ascending and keep hierarchy. If necessary add String with code of higher level departments, for example here we have strings with K1, but we havent separate String "K1". After sorting result must be

ascending sort:
        “K1”
        “K1\SK1”
        “K1\SK1\SSK1”
        “K1\SK1\SSK2”
        “K1\SK2”
        “K2”
        “K2\SK1”
        “K2\SK1\SSK1”
        “K2\SK1\SSK2”

descending sort:
        “K2”
        “K2\SK1”
        “K2\SK1\SSK2”
        “K2\SK2\SSK1”
        “K1”
        “K1\SK2”
        “K1\SK1”
        “K1\SK1\SSK2”
        “K1\SK1\SSK1”

And the question is how to sort departments descending with keep hierarchy? When im add Strings in TreeSet its Ok, natural sorting does it work and sort sodes ascending. But when I try to sort descending with Comparator it sorts without keeping hierarchy, as expected. As i think, i need to go tree from right to left on parent nodes. But how to do it? Here is my code:

    public class SortDepartment {

/**
 * Adds departments and sorts it in natural sorting in set
 * @param departments
 * @return
 */
public Set<String> addDepartmentIfNecessaryAndSortAscending(List<String> departments){

    Set<String> result = new TreeSet<>();
    String temp;
    for(int i = 0; i < departments.size(); i++) {

        if(departments.get(i).contains("\\")) {
            temp = departments.get(i).substring(0, departments.get(i).lastIndexOf("\\"));
            result.add(temp);
        }
        result.add(departments.get(i));
    }
    return result;
}


/**
 * Sorts departments descending
 * @param departments
 */
public Set<String> sortDepartmentDescending(Set<String> departments){

    Set<String> result =  new TreeSet<>(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o2.compareTo(o1);
        }
    });

    result.addAll(departments);
    return result;
}

}

mironec
  • 31
  • 5

1 Answers1

2

One way to do it would be to create a department class. This Department class would have two fields:

String name; int hierarchy;

Now you can create two comparators:

Comparator<Department> sortDescending = (d1, d2) -> {
    if(d1.hierarchy != d2.hierarchy)
        return Integer.compare(d2,d1)
    return String.compare(d2.name, d1.name)
}

and

Comparator<Department> sortAscending = (d1, d2) -> {
    if(d1.hierarchy != d2.hierarchy)
        return Integer.compare(d2,d1)
    return String.compare(d1.name, d2.name)
}

This can only work if you have a way of knowing the relative hierarchy of each department before initiating each object.

Ted Cassirer
  • 364
  • 1
  • 10