可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Can someone help me with this? Every example I find is about doing this alphabetically, while I need my elements sorted by date.
My ArrayList contains objects on which one of the datamembers is a DateTime object. On DateTime I can call the functions:
lt() // less-than
lteq() // less-than-or-equal-to
So to compare I could do something like:
if(myList.get(i).lt(myList.get(j))){
// ...
}
I don\'t really know what to do inside the if block. Any ideas?
回答1:
You can make your object comparable:
public static class MyObject implements Comparable<MyObject> {
private Date dateTime;
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date datetime) {
this.dateTime = datetime;
}
@Override
public int compareTo(MyObject o) {
return getDateTime().compareTo(o.getDateTime());
}
}
And then you sort it by calling:
Collections.sort(myList);
However sometimes you don\'t want to change your model, like when you want to sort on several different properties. In that case, you can create comparator on the fly:
Collections.sort(myList, new Comparator<MyObject>() {
public int compare(MyObject o1, MyObject o2) {
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
However, the above works only if you\'re certain that dateTime is not null at the time of comparison. It\'s wise to handle null as well to avoid NullPointerExceptions:
public static class MyObject implements Comparable<MyObject> {
private Date dateTime;
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date datetime) {
this.dateTime = datetime;
}
@Override
public int compareTo(MyObject o) {
if (getDateTime() == null || o.getDateTime() == null)
return 0;
return getDateTime().compareTo(o.getDateTime());
}
}
Or in the second example:
Collections.sort(myList, new Comparator<MyObject>() {
public int compare(MyObject o1, MyObject o2) {
if (o1.getDateTime() == null || o2.getDateTime() == null)
return 0;
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
回答2:
Since Java 8 the List interface provides the sort method. Combined with lambda expression the easiest solution would be
// sort DateTime typed list
list.sort((d1,d2) -> d1.compareTo(d2));
// or an object which has an DateTime attribute
list.sort((o1,o2) -> o1.getDateTime().compareTo(o2.getDateTime()));
// or like mentioned by Tunaki
list.sort(Comparator.comparing(o -> o.getDateTime()))
回答3:
You can use Collections.sort method. It\'s a static method. You pass it the list and a comparator. It uses a modified mergesort algorithm over the list. That\'s why you must pass it a comparator to do the pair comparisons.
Collections.sort(myList, new Comparator<MyObject> {
public int compare(MyObject o1, MyObject o2) {
DateTime a = o1.getDateTime();
DateTime b = o2.getDateTime();
if (a.lt(b))
return -1;
else if (a.lteq(b)) // it\'s equals
return 0;
else
return 1;
}
});
Note that if myList is of a comparable type (one that implements Comparable interface) (like Date, Integer or String) you can omit the comparator and the natural ordering will be used.
回答4:
Given MyObject
that has a DateTime
member with a getDateTime()
method, you can sort an ArrayList
that contains MyObject
elements by the DateTime
objects like this:
Collections.sort(myList, new Comparator<MyObject>() {
public int compare(MyObject o1, MyObject o2) {
return o1.getDateTime().lt(o2.getDateTime()) ? -1 : 1;
}
});
回答5:
list.sort(Comparator.comparing(o -> o.getDateTime()));
The best answer IMHO from Tunaki using Java 8 lambda
回答6:
This is how I solved:
Collections.sort(MyList, (o1, o2) -> o1.getLastModified().compareTo(o2.getLastModified()));
Hope it help you.
回答7:
All the answers here I found to be un-neccesarily complex for a simple problem (at least to an experienced java developer, which I am not). I had a similar problem and chanced upon this (and other) solutions, and though they provided a pointer, for a beginner I found as stated above. My solution, depends on where in the the Object your Date is, in this case, the date is the first element of the Object[] where dataVector is the ArrayList containing your Objects.
Collections.sort(dataVector, new Comparator<Object[]>() {
public int compare(Object[] o1, Object[] o2) {
return ((Date)o1[0]).compareTo(((Date)o2[0]));
}
});
回答8:
With introduction of Java 1.8, streams are very useful in solving this kind of problems:
Comparator <DateTime> myComparator = (arg1, arg2)
-> {
if(arg1.lt(arg2))
return -1;
else if (arg1.lteq(arg2))
return 0;
else
return 1;
};
ArrayList<DateTime> sortedList = myList
.stream()
.sorted(myComparator)
.collect(Collectors.toCollection(ArrayList::new));
回答9:
This may be an old response but I used some examples from this post to create a comparator that would sort an ArrayList
of HashMap<String, String>
by one object in the list, that being the timestamp.
I have these objects:
ArrayList<Map<String, String>> alList = new ArrayList<Map<String, String>>();
The map objects are as follows:
Map<String, Object> map = new HashMap<>();
// of course this is the actual formatted date below in the timestamp
map.put(\"timestamp\", \"MM/dd/yyyy HH:mm:ss\");
map.put(\"item1\", \"my text goes here\");
map.put(\"item2\", \"my text goes here\");
That mapping is what I use to load all my objects into the array list, using the alList.add(map)
function, within a loop.
Now, I created my own comparator:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class DateSorter implements Comparator {
public int compare(Object firstObjToCompare, Object secondObjToCompare) {
String firstDateString = ((HashMap<String, String>) firstObjToCompare).get(\"timestamp\");
String secondDateString = ((HashMap<String, String>) secondObjToCompare).get(\"timestamp\");
if (secondDateString == null || firstDateString == null) {
return 0;
}
// Convert to Dates
DateTimeFormatter dtf = DateTimeFormat.forPattern(\"MM/dd/yyyy HH:mm:ss\");
DateTime firstDate = dtf.parseDateTime(firstDateString);
DateTime secondDate = dtf.parseDateTime(secondDateString);
if (firstDate.isAfter(secondDate)) return -1;
else if (firstDate.isBefore(secondDate)) return 1;
else return 0;
}
}
I can now just call the Comparator at any time on the array and it will sort my array, giving me the Latest timestamp in position 0 (top of the list) and the earliest timestamp at the end of the list. New posts get put to the top basically.
Collections.sort(alList, new DateSorter());
This may help someone out, which is why I posted it. Take into consideration the return statements within the compare() function. There are 3 types of results. Returning 0 if they are equal, returning >0 if the first date is before the second date and returning <0 if the first date is after the second date. If you want your list to be reversed, then just switch those two return statements! Simple =]
回答10:
Pass the ArrayList In argument.
private static void order(ArrayList<Object> list) {
Collections.sort(list, new Comparator() {
public int compare(Object o2, Object o1) {
String x1 = o1.Date;
String x2 = o2.Date;
return x1.compareTo(x2);
}
});
}
回答11: