Google Tag Manager

2013/09/12

How to sort JTree nodes

Code

public static void sortTree(DefaultMutableTreeNode root) {
  Enumeration e = root.depthFirstEnumeration();
  while (e.hasMoreElements()) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
    if (!node.isLeaf()) {
      sort2(node);    // selection sort
      // sort3(node); // JDK 1.6.0: iterative merge sort
      // sort3(node); // JDK 1.7.0: TimSort
    }
  }
}

public static Comparator<DefaultMutableTreeNode> tnc = new Comparator<DefaultMutableTreeNode>() {
  @Override public int compare(DefaultMutableTreeNode a, DefaultMutableTreeNode b) {
    // ...
  }
};
// JDK 1.8.0
// a lambda expression Comparator
// Comparator< DefaultMutableTreeNode> tnc = Comparator.comparing(DefaultMutableTreeNode::isLeaf)
//                                                     .thenComparing(n -> n.getUserObject().toString());
// selection sort
public static void sort2(DefaultMutableTreeNode parent) {
  int n = parent.getChildCount();
  for (int i = 0; i < n - 1; i++) {
    int min = i;
    for (int j = i + 1; j < n; j++) {
      if (tnc.compare((DefaultMutableTreeNode) parent.getChildAt(min),
                      (DefaultMutableTreeNode) parent.getChildAt(j)) > 0) {
        min = j;
      }
    }
    if (i != min) {
      MutableTreeNode a = (MutableTreeNode) parent.getChildAt(i);
      MutableTreeNode b = (MutableTreeNode) parent.getChildAt(min);
      parent.insert(b, i);
      parent.insert(a, min);
    }
  }
}
public static void sort3(DefaultMutableTreeNode parent) {
  int n = parent.getChildCount();
  // @SuppressWarnings("unchecked")
  // Enumeration<DefaultMutableTreeNode> e = parent.children();
  // ArrayList<DefaultMutableTreeNode> children = Collections.list(e);
  List<DefaultMutableTreeNode> children = new ArrayList<>(n);
  for (int i = 0; i < n; i++) {
    children.add((DefaultMutableTreeNode) parent.getChildAt(i));
  }
  Collections.sort(children, tnc); // using Arrays.sort(...)
  parent.removeAllChildren();
  for (MutableTreeNode node: children) {
    parent.add(node);
  }
}

References