按两个过滤器排序字符串数组

时间:2016-11-27 12:31:49

标签: java sorting

我有以下字符串数组: " 0 11"," 22 34"," 5 14"," 22 13" ... 如何对其进行排序以使两个数字按顺序递增: " 0 11"," 5 14"," 22 13"," 22 34"?

3 个答案:

答案 0 :(得分:1)

您只需要实施适当的Comparator即可。像那样:

public static void main(String[] args) {
    String [] ar = {"0 11", "22 34", "5 14", "22 13"};

    Arrays.sort(ar, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            String [] value1 = o1.split(" ");
            String [] value2 = o2.split(" ");
            Integer o1First = Integer.valueOf(value1[0]);
            Integer o1Second = Integer.valueOf(value1[1]);
            Integer o2First = Integer.valueOf(value2[0]);
            Integer o2Second = Integer.valueOf(value2[1]);
            if (!o1First.equals(o2First))
                return o1First.compareTo(o2First);
            return o1Second.compareTo(o2Second);

        }
    });

    System.out.println(Arrays.toString(ar));
}

答案 1 :(得分:0)

使用Collections.sort(List, Comparator)试试这个,

Collections.sort(yourList, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        String[] split1 = s1.split(" ");
        String[] split2 = s2.split(" ");

        int n = split1[1].compareTo(split2[1]);

        if (n == 0) {
            return Integer.valueOf(split1[0]).compareTo(
                                  Integer.valueOf(split2[0]));
        }

        return n;
    }
});

答案 2 :(得分:0)

稍微冗长一点:

Arrays.sort(ar, Comparator.comparingInt((String s) -> Integer.parseInt(s.split(" ")[0]))
                    .thenComparingInt((String s) -> Integer.parseInt(s.split(" ")[1])));

不幸的是,Java目前没有内置对元组值类型的支持。否则代码可能会更短。