public static void optimizeSeparators(JPopupMenu menu) {
    boolean lastSeparator = true;

    for (int i = 0; i < menu.getComponentCount();) {
      if (menu.getComponent(i).isVisible() && menu.getComponent(i) instanceof JMenu)
        optimizeSeparators(((JMenu) menu.getComponent(i)).getPopupMenu());

      boolean separator = menu.getComponent(i) instanceof JPopupMenu.Separator;

      if (lastSeparator && separator)
        menu.remove(i);
      else
        i++;

      lastSeparator = separator;
    }

    if (menu.getComponentCount() > 0 &&
        menu.getComponent(menu.getComponentCount() - 1) instanceof JPopupMenu.Separator)
      menu.remove(menu.getComponentCount() - 1);
  }