嵌套属性值的collections.sort()



我正在研究数据表的分类功能。我有JSF Web控制器:

@Named
@ViewScoped
public class SearchPlayerController implements Serializable {
    private List<Player> playerList;
    @EJB
    PlayerFacade playerFacade;
    @PostConstruct
    public void init() {
        if (playerList == null) {
            playerList = playerFacade.findAll();
        }
    }
    // getters and setters
    *
    *
    *
}

在此控制器中,我有一个排序方法:

public String sortDataByClubName(final String dir) {
    Collections.sort(playerList, (Player a, Player b) -> {
        if(a.getClubId().getClubName()
            .equals(b.getClubId().getClubName())) {
            return 0;
        } else if(a.getClubId().getClubName() == null) {
            return -1;
        } else if(b.getClubId().getClubName() == null) {
            return 1;
        } else {
            if(dir.equals("asc")) {
                return a.getClubId().getClubName()
                    .compareTo(b.getClubId().getClubName());
            } else {
                return b.getClubId().getClubName()
                    .compareTo(a.getClubId().getClubName());
            }
        }
    });
    return null;
}

调用页面视图上的排序后,它将抛出NullPointerException。我认为主要原因是在Comparator内部无法读取clubName的值,该值应在获得俱乐部对象后可以访问。是否有可能比较嵌套属性的值?

您似乎仅在Player.getClubId().getClubName()上进行排序。似乎应该检查getClubId()getClubName()的NULL。这就是我的方式:

public class PlayerComparator implements Comparator<Player> {
    private String dir; // Populate with constructor
    public int compare(Player a, Player b) {
        int result = nullCheck(a.getClubId(), b.getClubId());
        if(result != 0) {
            return result;
        }
        String aname = a.getClubId().getClubName();
        String bname = b.getClubId().getClubName();
        result = nullCheck(aname, bname);
        if(result != 0) {
            return result;
        }
        result = aname.compareTo(bname);
        if("asc".equals(dir)) {   // No NPE thrown if `dir` is null
            result = -1 * result;
        }
        return result;
    }
    private int nullCheck(Object a, Object b) {
        if(a == null) { return -1; }
        if(b == null) { return 1; }
        return 0;
    }
}

相关内容

  • 没有找到相关文章

最新更新