TreeSet自定义比较器Algo ..字符串比较

时间:2011-11-11 10:40:52

标签: java comparator treeset

从提供的输入字符串:

  

{“200,400,7,1”,“100,0,1,1”,“200,200,3,1”,“0,400,11,1”,   “407,308,5,1”,“100,600,9,1”},

我在TreeSet中添加相同内容并希望它按第3个元素顺序排序,因此预期输出将是:

  

(100,0,1,1)(200,200,3,1)(407,308,5,1)(200,400,7,1)(100,600,9,1)(0,400,11,1)

但我的实际输出是:

  

(100,0,1,1)(0,400,11,1)(200,200,3,1)(407,308,5,1)(200,400,7,1)(100,600,9,1)

但由于11的字符串比较小于9,但就整数而言,11> 9。我的预期产量变得不同了。建议我解决同样的问题。

import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetComparator {

    public static void main(String[] args) {
        Comparator<String> comparator = new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                String aStr = a;
                String bStr = b;
                String[] splitA = aStr.split(",");
                String[] splitB = bStr.split(",");

                return splitA[2].compareTo(splitB[2]);
            }
        };

        String[] arr = { "200,400,7,1", "100,0,1,1", "200,200,3,1",
                "0,400,11,1", "407,308,5,1", "100,600,9,1" };

        TreeSet<String> ts = new TreeSet<String>(comparator);
        for (String str : arr) {
            ts.add(str);
        }

        for (String element : ts)
            System.out.print(element + " ");

    }
}

1 个答案:

答案 0 :(得分:10)

您按照字典顺序排序("123"之前的"20"),您需要做的是将它们转换为整数,然后进行比较:

return splitA[2].compareTo(splitB[2]);

但:

return Integer.valueOf(splitA[2]).compareTo(Integer.valueOf(splitB[2]));

然而,更简洁的方法是创建一个包含这4个不同值的自定义对象,然后创建一个Comparator来比较这个对象的3 rd 值:

以下内容:

public class Main {
    public static void main (String[] args) {

        Comparator<CustomObject> sortOn3rdValue = new Comparator<CustomObject>() {
            @Override
            public int compare(CustomObject o1, CustomObject o2) {
                return o1.v3 < o2.v3 ? -1 : o1.v3 > o2.v3 ? 1 : 0;
            }
        };

        Set<CustomObject> objects = new TreeSet<CustomObject>(sortOn3rdValue);

        String[] arr = { "200,400,7,1", "100,0,1,1", "200,200,3,1", "0,400,11,1", "407,308,5,1", "100,600,9,1" };

        for(String a : arr) {
            objects.add(new CustomObject(a.split(",")));
        }

        for(CustomObject co : objects) {
            System.out.println(co);
        }
    }
}

class CustomObject {

    final int v1, v2, v3, v4;

    CustomObject(String[] strValues) {
        // assume strValues.lenght == 4
        v1 = Integer.valueOf(strValues[0]);
        v2 = Integer.valueOf(strValues[1]);
        v3 = Integer.valueOf(strValues[2]);
        v4 = Integer.valueOf(strValues[3]);
    }

    @Override
    public String toString() {
        return String.format("(%d,%d,%d,%d)", v1, v2, v3, v4);
    }
}

会打印:

(100,0,1,1)
(200,200,3,1)
(407,308,5,1)
(200,400,7,1)
(100,600,9,1)
(0,400,11,1)