Order a LIST based on another LIST

Asked

Viewed 133 times

3

I have a class that has a property that is another class. Follow example:

Menu Class

public class Menu implements Serializable {

    private static final long serialVersionUID = 1L;
    private Long id;
    private String descricao;
    private Integer orderVisibilidade;
    private GrupoMenu grupoMenu;
}

Grupomenu class

public class GrupoMenu  implements Serializable {

    private static final long serialVersionUID = 1L;
    private Long id;
    private String descricao;
    private Integer ordemVisibilidade;
}

Well, I have a MENU LIST List<Menu> listMenu.

I created a class to sort through the field ordemVisibilidade class GrupoMenu and it worked.

As I’m making the ordination call:

OrdenaMenuPorGrupoMenu ordenaMenuGrupoMenu = new OrdenaMenuPorGrupoMenu();
Collections.sort(listMenu, ordenaMenuGrupoMenu);

Ordenamenuporgrupomenu

public class OrdenaMenuPorGrupoMenu implements Comparator<Menu> {

    @Override
    public int compare(Menu o1, Menu o2) {
        return o1.getGrupoMenu().getOrdemVisibilidade().compareTo(o2.getGrupoMenu().getOrdemVisibilidade());
    }

}

However, I must order also by the field orderVisibilidade class Menu, I mean, I need to sort the group and then for each group to sort the menus.

If I order by GrupoMenu and then by Menu, he reorders everything just by Menu. How do I make that comparison?

  • 1

    You have to show how you order it. That must be the problem.

  • GrupoMenu contains one or more Menus?

  • Since it is solved, a tip, which in my view is more efficient, would implement the interface Comparable in the class itself, with the method itself in the class, without using extra classes.

1 answer

3


How about you try that?

public class OrdenaMenuPorVisibilidade implements Comparator<Menu> {

    @Override
    public int compare(Menu o1, Menu o2) {
        int d = o1.getGrupoMenu().getOrdemVisibilidade().compareTo(o2.getGrupoMenu().getOrdemVisibilidade());
        if (d != 0) return d;
        return o1.getOrderVisibilidade().compareTo(o2.getOrderVisibilidade());
    }

}

He tries to compare it to the visibility of the group. If you tie (which will happen if both menus are in the same group), then it uses menu visibility to unpack.

  • 1

    The ordination worked. Thank you very much for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.