java 根据标签对 f:selectItems 列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5007959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:02:30  来源:igfitidea点击:

Sort f:selectItems list based on labels

javajsf

提问by shaleen

I have a selectItem list of values and labels. Data is fetched from database and the selectItem list has following values:

我有一个值和标签的 selectItem 列表。从数据库中获取数据并且 selectItem 列表具有以下值:

<1,100-500>
<2,1000-1500>
<3,500-1000>

Here 1, 2, 3 are the values for selectItem list and '100-500', '1000-1500' and '500-1000' are labels respectively. As you can see, the list is already sorted based on labels. But my requirement is that the list should be displayed in the dropdown as follows:

这里 1、2、3 是 selectItem 列表的值,'100-500'、'1000-1500' 和 '500-1000' 分别是标签。如您所见,该列表已经根据标签进行了排序。但我的要求是该列表应显示在下拉列表中,如下所示:

100-500
500-1000
1000-1500

Can anyone please suggest a solution?

任何人都可以提出解决方案吗?

回答by JB Nizet

If you can't modify the code which fetches the SelectItem instances from the DB so that the come sorted as you'd like, then you have to sort them yourself :

如果您无法修改从数据库中获取 SelectItem 实例的代码,以便按照您的意愿对它们进行排序,那么您必须自己对它们进行排序:

// this gets you a list which is not sorted as you would like
List<SelectItem> list = getMasterValues("Staff Range");

// you need to sort the list before displaying it. 
// To sort the list, you need a Comparator which will tell the sorting
// algorithm how to order the items
Comparator<SelectItem> comparator = new Comparator<SelectItem>() {
    @Override
    public int compare(SelectItem s1, SelectItem s2) {
        // the items must be compared based on their value (assuming String or Integer value here)
        return s1.getValue().compareTo(s2.getValue());
    }
};

// now that you have the comparator, sort the list using it :
Collections.sort(list, comparator);

// and now iterate over the list to display it :
for (SelectItem item : list) {
    System.out.println("value = " + item.getValue() + "; label = " + item.getLabel());
}

回答by mre

Here's an example program I quickly wrote that uses a custom comparator:

这是我快速编写的使用自定义比较器的示例程序:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.JLabel;

public class StrangeSort
{
    static List<JLabel> listOfLabels = new ArrayList<JLabel>();

    @SuppressWarnings("unchecked")
    public static void main(String[] args)
    {
        listOfLabels.add(new JLabel("100-500"));
        listOfLabels.add(new JLabel("1000-1500"));
        listOfLabels.add(new JLabel("500-1000"));

        System.out.println("Before:");
        for(JLabel label: listOfLabels)
        {
            System.out.println(label.getText());
        }

        Collections.sort(listOfLabels, new LabelComparator());

        System.out.println("After:");
        for(JLabel label: listOfLabels)
        {
            System.out.println(label.getText());
        }

    }

    static class LabelComparator implements Comparator
    {
        public int compare(Object obj1, Object obj2)
        {
            // Get labels
            JLabel label1 = (JLabel) obj1;
            JLabel label2 = (JLabel) obj2;

            // Get text
            String[] label1Text = label1.getText().split("-");
            String[] label2Text = label2.getText().split("-");

            // Convert to integers
            int label1Value = Integer.parseInt(label1Text[0]);
            int label2Value = Integer.parseInt(label2Text[0]);

            // Compare values
            if (label1Value > label2Value)
            {
                return 1;
            }
            else if (label1Value < label2Value)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    }
}

Output:

输出:

Before:
100-500
1000-1500
500-1000
After:
100-500
500-1000
1000-1500

回答by Melloware

I use Commons BeanUtilsand do it with 1 line of code....

我使用Commons BeanUtils并用 1 行代码完成它....

// sort by label
Collections.sort(selectItems, new BeanComparator<>("label"));

OR...

或者...

// sort by value
Collections.sort(selectItems, new BeanComparator<>("value"));

回答by DwB

Sort by Label

按标签排序

Take a look at the code posted by "JB Nizet". It sorts by value. If you change
return s1.getValue().compareTo(s2.getValue());
to the following:
return s1.getLabel().compareTo(s2.getLabel());
It will sort by label.

看看“JB Nizet”发布的代码。它按值排序。如果更改
return s1.getValue().compareTo(s2.getValue());
为以下内容:
return s1.getLabel().compareTo(s2.getLabel());
它将按标签排序。

Sort Label Numerically

按数字对标签进行排序

The above will sort by string value. Which means that 1 is less than 5 (i.e. 1000 < 500). The next step is to convert the label to a number and compare it. For this use a variation of the following:

以上将按字符串值排序。这意味着 1 小于 5(即 1000 < 500)。下一步是将标签转换为数字并进行比较。为此,请使用以下变体:


int value1 = Integer.parseInt(s1.getLabel());
int value2 = Integer.parseInt(s2.getLabel());
return value1 - value2;

回答by shaleen

Thanks you very much for your help. I am getting the desired result. Please find below the code for your reference.

非常感谢您的帮助。我得到了想要的结果。请在下面找到代码供您参考。

  /**
   * This is a custom comparator used for numeric sorting based on labels 
  */
  static class LabelComparator implements Comparator {
        public int compare(Object obj1, Object obj2) {
              // Get labels
              SelectItem label1 = (SelectItem) obj1;
              SelectItem label2 = (SelectItem) obj2;
              // Get text
              String[] label1Text = label1.getLabel().split("-");
              String[] label2Text = label2.getLabel().split("-");
              // Convert to integers
              int label1Value = Integer.parseInt(label1Text[0]);
              int label2Value = Integer.parseInt(label2Text[0]);
              // Compare values
              if (label1Value > label2Value) {
                    return 1;
              } else if (label1Value < label2Value) {
                    return -1;
              } else {
                    return 0;
              }
        }
  }

  /**
   * Method to populate values  
  */
  public void init() {
        List rangeList = (List) CodeManagerUtil
                    .getValue("Staff Range");
        Collections.sort(rangeList, new LabelComparator());
        if (rangeList != null) {
              setRangeList(rangeList );
        }
  }