Reputation: 13348
Am using following code in arraylist date ascending order its works fine.but i need to modify that code to get data between start and end date from arraylist.
How can i modify that based on my requirements?
Ascending order code(working fine)
Collections.sort(adapter.modelValues, new Comparator<Actors>() {
@Override
public int compare(Actors lhs, Actors rhs) {
Date d1 = null, d2 = null;
try {
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
String a = lhs.getlastaction();
String b = rhs.getlastaction();
d1 = f.parse(a);
d2 = f.parse(b);
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(e.getMessage()), Toast.LENGTH_LONG).show();
}
return d1.compareTo(d2);
}
});
Date between code(not working)
Collections.sort(adapter.modelValues, new Comparator<Actors>() {
@Override
public int compare(Actors lhs, Actors rhs) {
Date d1 = null, d2 = null, d3 = null, d4 = null;
int rval = -1;
try {
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
String a = lhs.getlastaction();
String b = rhs.getlastaction();
String startdat = "28-Jul-2015";
String enddat = "21-Aug-2015";
d1 = f.parse(a);
d2 = f.parse(b);
d3 = f.parse(startdat);
d4 = f.parse(enddat);
if (d1.before(d4) && (d1.after(d3))) {
rval = d1.compareTo(d4);
}
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(e.getMessage()), Toast.LENGTH_LONG).show();
}
return rval;
}
});
after sorting its display all values in array list.but i need between two dates(start,end) values.. How can i solve this issue?
Upvotes: 0
Views: 1881
Reputation: 1933
try this code
private ArrayList<Actors> getNewList(ArrayList<Actors> oldList) throws java.text.ParseException {
ArrayList<Actors> newList = new ArrayList<Actors>();
Date d1 = null, d2 = null, d3 = null, d4 = null;
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
String startdat = "28-Jul-2015";
String enddat = "21-Aug-2015";
d3 = f.parse(startdat);
d4 = f.parse(enddat);
for (int i = 0; i < oldList.size(); i++) {
String b = oldList.get(i).getlastaction();
d2 = f.parse(b);
if (d2.compareTo(d3) >= 0 && d2.compareTo(d4) <= 0) {
newList.add(oldList.get(i));
}
}
return newList;
}
Upvotes: 8
Reputation: 54692
the compare method returns the comparision value of two element by using which a sort of the collection's element is done.
To do your desired operation you can do the following. create your own method by passing the collection. then iterate through each element and if the date is not in-between your two dates then you can remove ( or add the expected dates in another List).
Upvotes: 0