说我有一个字符串数组:
String[] array = {
"2183417234 somerandomtexthere",
"1234123656 somemorerandomtexthere",
"1093241066 andevenmore",
"1243981234 you get what i mean",
//etc
};
我如何使用字符串开头的long(它是一个长整数)对这个数组进行排序,所以它最终看起来像这样:
String[] array = {
"1093241066 andevenmore",
"1234123656 somemorerandomtexthere",
"1243981234 you get what i mean",
"2183417234 somerandomtexthere",
//etc
};
我已经尝试过将它变成一个arraylist并使用Collections #sort来创建我自己的比较器,使用一个有序的map / tree map而我无法理解它。 感谢。
答案 0 :(得分:2)
使用此功能:
static long comparedValue(String s) {
return Long.valueOf(s.substring(0, s.indexOf(' ')));
}
然后根据它定义比较器:
public int compare(String left, String right) {
return comparedValue(left) - comparedValue(right);
}
答案 1 :(得分:1)
使用Google Guava:
List<String> unsorted = Arrays.asList(array);
Function<String, Long> longFunction = new Function<String, Long>() {
@Override public Long apply(String input) {
return Long.valueOf(input.split(" ")[0]);
}
};
List<String> sorted = Ordering.natural().onResultOf(longFunction).immutableSortedCopy(unsorted);
或者如果你不想使用List(你应该总是喜欢集合到数组):
Arrays.sort(array, Ordering.natural().onResultOf(longFunction));
答案 2 :(得分:0)
您展示的输入效果非常好。但那是因为它们都具有相同的位数。
public static void main(String[] args) {
String[] array = { "2183417234 somerandomtexthere",
"1234123656 somemorerandomtexthere", "1093241066 andevenmore",
"1243981234 you get what i mean", "999 little shorter"
// etc
};
List<String> list = Arrays.asList(array);
Collections.sort(list);
System.out.println(list);
}
当您使用较短的数字时,问题开始发生 - 如上所示999 ......
输出将是:
[1093241066 andevenmore, 1234123656 somemorerandomtexthere, 1243981234 you get what i mean, 2183417234 somerandomtexthere, 999 little shorter]
所以,为了让它始终工作 - 你需要你的自定义比较器,它能够分割给定的字符串,然后从中取出数字部分,并比较它们。使用@Marko Topolik解决方案:
static long comparedValue(String s) {
return Long.valueOf(s.substring(0, s.indexOf(' ')));
}
public int compare(String left, String right) {
long result = comparedValue(left) - comparedValue(right);
boolean numberPartAreEqual = result == 0;
if (numberPartAreEqual) {
result = left.compareTo(right);
}
return (int) result;
}
答案 3 :(得分:0)
自定义比较器应该可以正常工作:
public class LongPrefixComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
final long pref1 = getPrefixValue(s1);
final long pref2 = getPrefixValue(s2);
return s1 == s2 ? 0 : s1 < s2 ? -1 : 1;
}
private static long getPrefixValue(String stg) {
int len = stg.indexOf(' ');
if (len > 0) {
try {
return Long.parseLong(stg.substring(0, len));
catch (NumberFormatException ignored) {}
}
return 0L;
}
}