简体   繁体   English

根据值对arraylist进行排序

[英]order arraylist based on values

Here is the actual scenario. 这是实际情况。 Have a VO 有VO

Name Usagecount  returncount number
A   0       0       123
B   1       1           234
C   0       2       345
D   2       3       546

First it should sort based on usage count, descending order. 首先,它应该根据使用次数,降序进行排序。 If same usage count found then it should sort based on return code in ascending order.If same return count is found then it should sorted with number in ascending order. 如果找到相同的使用计数,则应基于返回码以升序排序;如果找到相同的返回计数,则应以数字升序排序。 When i tried this below code snippet 当我尝试下面的代码片段时

public class SomeComparator implements Comparator<SomeVO> {
        @Override
        public int compare(SomeVO o1, SomeVO o2) {
            int value1 = o2.getUsageCount().compareTo(o1.getUsageCount());
            if (value1 == 0) {
                int value2 = o1.getNumberofReturns().compareTo(o2.getNumberofReturns());
                if (value2 == 0) {
                    return o1.getNumber().compareTo(o2.getNumber());
                } else {
                    return value2;
                }
            }
            return value1;
        }
    }

I get output D,B,C, but i am expecting it as D,B,A,C. 我得到输出D,B,C,但我期望它是D,B,A,C。

No. You should be able to implement all sorting logic in your Comparator (or Comparable ) implementation. 不能。您应该能够在Comparator (或Comparable )实现中实现所有排序逻辑。

For instance (pseudo-code): 例如(伪代码):

  • Compare by color (lexicographically apparently, ie your example puts "Black" before "black") 按颜色进行比较(按词典顺序显示,即您的示例将“ Black”放在“ black”之前)
  • If equal, compare by seats 如果相等,则按席位进行比较

Your Collections.sort invocation will then perform the appropriate sort based on your logic within compare or compareTo . 然后,您的Collections.sort调用将根据comparecompareTo逻辑执行适当的排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM