Например вот так. Не оптимизировал :-)
package my.com;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Paths {
public static void main(String[] args) {
String str = "A1, A1\\BB1\\CCC1, A2\\BB1, A2\\BB1\\CCC1";
ArrayList<String> paths = new ArrayList<String>(Arrays.asList(str.split(",")));
System.out.println("====== Беган =======");
System.out.println("Было");
for(String i:paths){
System.out.println(i);
}
Set<String> out = new TreeSet<String>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
for(String i : paths) {
ArrayList<String> path = new ArrayList<String>(Arrays.asList(i.trim().split("\\\\")));
for(int j = 1; j <= path.size(); j++) {
List<String> s = path.subList(0, j);
out.add(String.join("\\",s));
}
}
System.out.println("=================");
System.out.println("Сортировка туда");
for(String i:out) {
System.out.println(i);
}
System.out.println("=================");
System.out.println("Сортировка обратно");
Set<String> out1 = new TreeSet<String>();
out1.addAll(out);
for(String i:out1) {
System.out.println(i);
}
System.out.println("======= Доне ======");
}
}
====== Беган =======
Было
A1
A1\BB1\CCC1
A2\BB1
A2\BB1\CCC1
=================
Сортировка туда
A2\BB1\CCC1
A2\BB1
A2
A1\BB1\CCC1
A1\BB1
A1
=================
Сортировка обратно
A1
A1\BB1
A1\BB1\CCC1
A2
A2\BB1
A2\BB1\CCC1
======= Доне ======