Java 按日期排序具有多种数据类型的Arraylist(数字)
这就是我所拥有的。我正在扫描txt并将其作为字符串(每行)传递给数组。我需要按日期分类Java 按日期排序具有多种数据类型的Arraylist(数字),java,sorting,arraylist,Java,Sorting,Arraylist,这就是我所拥有的。我正在扫描txt并将其作为字符串(每行)传递给数组。我需要按日期分类 package stocktest; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; /** */ public class StockTest { /** * @param args the command line arguments
package stocktest;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
*/
public class StockTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ArrayList aList = new ArrayList();
java.io.File file = new java.io.File("transactions.txt");
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
String data = input.nextLine();
aList.add(data);
System.out.println(aList);
}
} catch (FileNotFoundException e) {
System.err.format("File does not exist/n");
}
}
}
transaction.txt中的每一行如下所示
购买,2002年1月2日,IBM,30135.00
我需要按日期对清单进行排序。
你觉得我该怎么办?
提前谢谢 首先,为什么不试着用“,”来解析每一行,然后把它放在一个有状态和方法的类中,这样你就可以使用comparator对数组列表进行排序了,见我的示例
private-List-orderdto代码>
公共类OrderDtoDateDescComparator实现Comparator{
@凌驾
公共int比较(OrderDTO到OrderDTO,OrderDTO到其他){
if(orderDTO.getDateCreated()!=null和其他.getDateCreated()!=null){
返回orderDTO.getDateCreated().compareTo(other.getDateCreated());
}else if(orderDTO.getDateCreated()!=null和其他.getDateCreated()=null){
返回1;
}else if(orderDTO.getDateCreated()==null&&other.getDateCreated()!=null){
返回-1;
}
返回0;
}
}
Collections.sort(this.orderDTOs,new orderdtodatedscomparator())代码>
现在看,这很容易。事实就是这样 这是一个很酷的比较器用例
Collections.sort(aList, new Comparator<String>() {
public int compare(String s1, String s2) {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy");
try {
Date d1 = format.parse(s1.split(",")[1]);
Date d2 = format.parse(s2.split(",")[1]);
return d1.compareTo(d2);
} catch (ParseException e) {
// handle exception
}
}
});
Collections.sort(列表,新比较器(){
公共整数比较(字符串s1、字符串s2){
SimpleDataFormat格式=新的SimpleDataFormat(“MM/dd/yy”);
试一试{
日期d1=format.parse(s1.split(“,”[1]);
Date d2=format.parse(s2.split(“,”[1]);
返回d1。比较(d2);
}捕获(解析异常){
//处理异常
}
}
});
我认为您应该对数组进行排序
Collections.sort(aList, new Comparator<String>() {
public int compare(String s1, String s2) {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy");
try {
Date d1 = format.parse(s1.split(",")[1]);
Date d2 = format.parse(s2.split(",")[1]);
return d1.compareTo(d2);
} catch (ParseException e) {
// handle exception
}
}
});