排序的ArrayList<串GT;自定义比较 [英] Sorting an ArrayList<String> with custom Comparator

查看:151
本文介绍了排序的ArrayList<串GT;自定义比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想排序的的ArrayList<串GT; 使用自定义的比较。我的要求是, XX 字符串应该是第一个字符串,其他人应该遵循自然顺序。

I am trying to sort an ArrayList<String> using custom Comparator. My requirement is that XX String should be the first String, others should follow natural ordering.

我需要:[XX,XX,1,5,9,A,D,G,Q,Z]

  我所得到的[1,5,9,A,D,G,Q,Z,XX,XX]

I need : [XX, XX, 1, 5, 9, A, D, G, Q, Z]
What I am getting is [1, 5, 9, A, D, G, Q, Z, XX, XX]

以下是我的code:

public class Test {
    public static void main(String[] args) 
    {
        List<String> list = new ArrayList<String>();
        list.add("Z");
        list.add("5");
        list.add("D");
        list.add("G");
        list.add("XX");     
        list.add("9");
        list.add("Q");
        list.add("XX");
        list.add("1");
        list.add("A");      
        Collections.sort(list, new CustomComparator());     
        System.out.println(list);       
    }
}
class CustomComparator implements Comparator<String>
{
    @Override
    public int compare(String o1, String o2) {      
        if(o2.equals("XX")) {
            return -1;
        }       
        return o1.compareTo(o2);
    }   
}

修改:如果我改变比较逻辑:

EDIT: if i change comparator logic to:

@Override
    public int compare(String o1, String o2) {      
        if(o2.equals("XX")) {
            return 1;
        }       
        return o1.compareTo(o2);
    }

我越来越:

[1,XX,9,A,Q,XX,5,D,G,Z]

[1, XX, 9, A, Q, XX, 5, D, G, Z]

请让我知道如何着手。先谢谢了。

Please let me know how to proceed. Thanks in advance.

推荐答案

使用此比较实施

@Override
public int compare(String o1, String o2) {      
    if(o2.equals("XX")) {
        return o1.equals("XX") ? 0 : 1;
    } else if (o1.equals("XX")) {
        return -1;
    }
    return o1.compareTo(o2);
}  

原因:超越的问题时使用-1或1它来保证O1和O2的所有可能的元组明确的秩序,看到的的javadoc

Reason: Beyond the question when to use -1 or 1 it is important to guarantee a clear order for all possible tuples of o1 and o2, see javadoc:

...]
实现者必须确保的sgn(比较(X,Y))== -sgn(比较(Y,X)),对所有的x和y。 (这意味着比较(X,Y)当且仅当比较(Y,X)抛出一个异常必须抛出异常。)

[...] The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

实现程序还必须确保关系是可传递的:((比较(X,Y)> 0)及及(对比(Y,Z)> 0))表示比较(X,Z)> 0。
[...]

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0. [...]

这篇关于排序的ArrayList&LT;串GT;自定义比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆