How to sort Date which is in string format in java?
try this
Collections.sort(datestring, new Comparator<String>() {
DateFormat f = new SimpleDateFormat("MM/dd/yyyy '@'hh:mm a");
@Override
public int compare(String o1, String o2) {
try {
return f.parse(o1).compareTo(f.parse(o2));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
});
or with Java 8
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy '@'hh:mm a");
Collections.sort(datestring, (s1, s2) -> LocalDateTime.parse(s1, formatter).
compareTo(LocalDateTime.parse(s2, formatter)));
How to sort dates of type string in java
Implement Comparable
in your Person
class:
public class Person implements Comparable<Person> {
public int compareTo(Person person) {
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
return sdf.parse(this.dateString).compareTo(sdf.parse(person.dateString));
}
}
Replace "YYYY-MM-dd"
with the format of your date string.
How to sort objects according to string date in java
LocalDate
as your property
The best solution is to alter your Customer
class to use LocalDate
class as the type of your property.
Tip: Use a more descriptive name for your member fields that just date
.
public class Customer {
public LocalDate firstContact ;
…
}
Now your Comparator
becomes quite simple, as the LocalDate
class already implements the Comparable
interface and its compareTo
method.
public static Comparator< Customer > CustomerComparator = new Comparator< Customer >()
{
@Override
public int compare( Customer c1 , Customer c2 ) {
return ( c1.firstContact.compareTo( c2.firstContact ) ) ;
}
};
If you cannot change the data type of your class property, see the correct Answer by Ezequiel.
How to sort 'MMM YYYY' date string according to date?
Create a Stream
of the given strings, parse each string of the Stream
into YearMonth
, sort the Stream
, map each YearMonth
element to the original format and finally, collect the Stream
into a collection.
Demo:
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String args[]){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM uuuu", Locale.ENGLISH);
List<String> sorted = Stream.of(
"Sep 2019",
"Oct 2018",
"Nov 2019",
"Oct 2021",
"Nov 2011"
)
.map(s -> YearMonth.parse(s, dtf))
.sorted()
.map(ym -> dtf.format(ym))
.collect(Collectors.toList());
// Display the list
sorted.forEach(System.out::println);
}
}
Output:
Nov 2011
Oct 2018
Sep 2019
Nov 2019
Oct 2021
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time
.
Java program to sort a list of date which is in format dd MMM yyyy
Radix Sort is your friend. Just sort strings with this algorithm. This is optimal solution.
Sort date strings in map
Create a custom comparator for the TreeMap
:
class DateComparator implements Comparator<String>, Serializable {
public int compare(String date1, String date2) {
int date1Int = convertDateToInteger(date1);
int date2Int = convertDateToInteger(date2);
return date1Int - date2Int;
}
// converts date string with format MM/DD/YYYY to integer of value YYYYMMDD
private int convertDateToInteger(String date) {
String[] tokens = date.split("/");
return Integer.parseInt(tokens[2] + tokens[0] + tokens[1]);
}
}
TreeMap<String, Integer> treeMap = new TreeMap<>(new DateComparator());
This has the benefit of avoiding Date
objects, which may slow put
operations down.
Date strings like 06/15/2015
or 05/15/2015
are converted to comparable integer equivalents (20150615
and 20150515
respectively) in keeping with their chronological order.
You can then add key/value pairs as usual, the keys will be ordered as per the comparator:
treeMap.put("06/15/2015", 1);
treeMap.put("05/15/2015", 2);
treeMap.put("01/15/2016", 4);
treeMap.put("07/15/2015", 3);
treeMap.put("02/15/2016", 5);
Sorting Java List of objects using string date
Use this
Collections.sort(newsList, new Comparator<NewsFeed>() {
DateFormat f = new SimpleDateFormat("dd/MM/yyyy");//or your pattern
@Override
public int compare(NewsFeed o1, NewsFeed o2) {
try {
return f.parse(o1.getDate()).compareTo(f.parse(o2.getDate()));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
});
With Comparable
it looks like this:
public class NewsFeed implements Comparable<NewsFeed>{
//your fields and getters/setters
private DateFormat f = new SimpleDateFormat("dd/MM/yyyy");//or your pattern
@Override
public int compareTo(NewsFeed o) {
try {
return f.parse(this.getDate()).compareTo(f.parse(o.getDate()));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
}
How to sort a list of objects by date when date is String?
I think that you can create a custom comparator with an structure similar to the below:
Collections.sort(datestring, new Comparator<String>() {
DateFormat df = new SimpleDateFormat("your format");
@Override
public int compare(String s1, String s2) {
try {
return df.parse(s1).compareTo(df.parse(s2));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
});
Related Topics
"Unable to Acquire Application Service" Error While Launching Eclipse
Dynamic Graphics Object Painting
Fastest Way to Iterate Over All the Chars in a String
Why Do We Need Immutable Class
How to Call the Overridden Method of a Superclass
Reverse Each Individual Word of "Hello World" String with Java
Jsch Algorithm Negotiation Fail
In Java, When Should I Create a Checked Exception, and When Should It Be a Runtime Exception
Storing a Map<String,String> Using JPA
Java Ioexception "Too Many Open Files"
How to Detect Submit Button Clicked in Multiple Submit Buttons Scenario in Single Action Class
What's Alternative to Singleton
Is There a Fixed Sized Queue Which Removes Excessive Elements
How Is Hashcode() Calculated in Java