Order a LIST based on another LIST

3

I have a class that has a property that is another class. Here's an 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;
}

GroupMenu 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 by the field ordemVisibilidade of class GrupoMenu and worked.

How am I doing the sort order:

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

OrderMenuForMenuGroup

public class OrdenaMenuPorGrupoMenu implements Comparator<Menu> {

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

}

However, I also need to sort by the orderVisibilidade field of the Menu class, that is, I need to sort the group and then for each group sort the menus.

If I have ordered by GrupoMenu and then Menu , it reorders everything only by Menu . How do I make this comparison?

    
asked by anonymous 16.01.2015 / 16:13

1 answer

3

How about trying this?

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());
    }

}

It tries to compare by group visibility. If it draws (which will happen if the two menus are in the same group), then it uses the menu visibility to break.

    
16.01.2015 / 16:59