[英]Sort array of strings by two filters
我有以下字符串数组:“ 0 11”,“ 22 34”,“ 5 14”,“ 22 13” ...如何对其进行排序,以便两个数字都按升序排列:“ 0 11”,“ 5 14”,“ 22 13”,“ 22 34”?
您只需要实现一个合适的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));
}
使用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;
}
});
稍微冗长一些:
Arrays.sort(ar, Comparator.comparingInt((String s) -> Integer.parseInt(s.split(" ")[0]))
.thenComparingInt((String s) -> Integer.parseInt(s.split(" ")[1])));
不幸的是,Java当前尚未内置对元组值类型的支持。 否则,代码可能会更短。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.