基于java中的值的SelectItem的Order List

时间:2017-06-09 04:21:27

标签: java primefaces jsf-2.2

我正在使用Primefaces 5.1和JSF 2.2。

我需要根据selectItem值排序SelectItemList列表。

List<SelectItem>mainList=new ArrayList<SelectItem>();
mainList.add(new SelectItem("1&Val1","Kumar"));
mainList.add(new SelectItem("4&Val4","Raju"));
mainList.add(new SelectItem("5&Val5","Suriya"));
mainList.add(new SelectItem("3&Val3","Kamal"));

1 个答案:

答案 0 :(得分:0)

您需要定义一种订购SelectItem类的方法。您可以通过实现Comparable接口并覆盖compareTo方法来实现此目的。

class SelectItem implements Comparable<SelectItem> {

    // constructor, getters, setters

    @Override
    public int compareTo(SelectItem other) {
        // implement logic that compares the values of the class the way that you want

        // maybe like this
        if(this.getValue() > other.getValue()) {
            return 1;
        } else if(this.getValue() < other.getValue()) {
            return -1;
        } else {
            return 0; // values are equal
        }
    }
}

现在,您可以使用Collections.sort()对商品列表进行排序。

List<SelectItem>mainList=new ArrayList<SelectItem>();
mainList.add(new SelectItem("1&Val1","Kumar"));
mainList.add(new SelectItem("4&Val4","Raju"));
mainList.add(new SelectItem("5&Val5","Suriya"));
mainList.add(new SelectItem("3&Val3","Kamal"));

Collections.sort(mainList); // now they are sorted