在java中,我有这个数组
String[][] data = new String[][]{
new String[]{"ABC", "A", "03/01/2009", "02/29/2016"},
new String[]{"ABC", "A", "08/31/2000", "02/17/2016"},
new String[]{"DEF", "A", "07/14/2004", "09/26/2007"},
new String[]{"ABC", "A", "11/15/2001", "12/18/1997"},
new String[]{"GHI", "B", "12/18/1997", "08/11/2006"},
new String[]{"DEF", "A", "11/12/1997", "06/18/1999"}
};
我想根据4列对其进行排序,我需要将第3和第4列转换为DATE以获取最新和最旧的日期,因此我的最终数据可能如下所示
ABC A 08/31/2000 02/29/2016
DEF A 11/12/1997 09/26/2007
GHI B 12/18/1997 08/11/2006
所有列都是字符串。
答案 0 :(得分:0)
您可以轻松地按此方式排序
public void sort2dArray() {
String[][] data = new String[][] {
new String[] { "ABC", "A", "03/01/2009", "02/29/2016"},
new String[] { "ABC", "A", "08/31/2000", "02/17/2016" },
new String[] { "DEF", "A", "07/14/2004", "09/26/2007" },
new String[] { "ABC", "A", "11/15/2001", "12/18/1997" },
new String[] { "GHI", "B", "12/18/1997", "08/11/2006" },
new String[] { "DEF", "A", "11/12/1997", "06/18/1999" } };
Arrays.sort(data,new Comparator<String[]>() {
@Override
public int compare(String[] o1, String[] o2) {
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("MM/dd/yyyy");
LocalDate o1Date = LocalDate.parse(o1[2], formatter);
LocalDate o2Date = LocalDate.parse(o2[2], formatter);
if (o1[0].equals(o2[0])) {
if (o1Date.isBefore(o2Date) || o1Date.isEqual(o2Date)) {
o2[2] = o1[2];
}
}
return LocalDate.parse(o2[3], formatter).compareTo(
LocalDate.parse(o1[3], formatter));
}
});
Map<String,String[]> map=new HashMap<>();
for(String[] s:Arrays.asList(data)) {
if(!map.containsKey(s[0])) {
map.put(s[0],s);
}
}
String[][] distinct=new String[map.size()][];
int i=0;
for(String k:map.keySet()) {
String a[]=map.get(k);
distinct[i]=a;
i++;
}
Arrays.stream(distinct).forEach(a->System.out.println(a[0]+" "+a[1]+" "+a[2]+" "+a[3]));
}
<强>输出:强>
ABC A 08/31/2000 02/29/2016
DEF A 11/12/1997 09/26/2007
GHI B 12/18/1997 08/11/2006