我有一组像
这样的字符串"12:00:10, some words here"
"12:10:32, some words here"
"13:02:46, Some words here"
"12:39:12, some words here"
如果时间是hh:mm:ss
格式,我如何对这些行进行排序以便获得此输出:
"12:00:10, some words here"
"12:10:32, some words here"
"12:39:12, some words here"
"12:39:12, some words here"
答案 0 :(得分:4)
不知道你正在使用什么类型的数据结构,但是如果使用Arrays,则会使用简单的Arrays.sort。
import java.util.Arrays;
public class A {
public static void main(String[] a) {
String[] str = new String[] { "12:00:10, some words here", "12:10:32, some words here",
"13:02:46, Some words here", "12:39:12, some words here" };
System.out.println("Before Sorting");
for(String s:str) {
System.out.println(s);
}
Arrays.sort(str);
System.out.println("After Sorting");
for(String s:str) {
System.out.println(s);
}
}
}
Output
Before Sorting
12:00:10, some words here
12:10:32, some words here
13:02:46, Some words here
12:39:12, some words here
After Sorting
12:00:10, some words here
12:10:32, some words here
12:39:12, some words here
13:02:46, Some words here
答案 1 :(得分:0)
我会给你一些提示,让你开始:
Map
,因为这组单词总是被分为时间戳,然后是所选单词。找到一种解析字符串的方法,以便您可以将时间戳存储为键,将单词存储为值。获取这些时间戳并对其进行排序,其中最高优先级为小时,最低优先级为秒。我这样做的一种方法是简单地取出冒号并比较这些时间戳的int
值。例如,在您的情况下,它将是:
// Unsorted
120010
121032
130246
123912
如果你按照int
值对它进行排序,它将如下所示:
// Sorted
120010
121032
123912
130246
为此找到一个排序只需要几秒钟,因为有这么多资源。
最后,由于您知道应如何订购,因此您可以将该逻辑应用于您在开头所做的Map
。而且你只需要用正确的格式打印出来。
希望这可以提供帮助并尝试发布代码,以便我们知道您可以在哪些方面进行改进。
答案 2 :(得分:0)
为您的String
值创建包装类,并为其实现Comparator
接口:
class Item implements Comparable<Item>
{
String value;
@Override
public int compareTo(final Item o)
{
return this.getNumericValue().compareTo(o.getNumericValue());
}
//Extract the numeric part from the string
public Integer getNumericValue()
{
final String[] pair = this.value.split(",");
return Integer.parseInt(pair[0].replace(":", ""));
}
}
然后对列表进行排序只需使用:
Collections.sort(list);