Java sorted list by date

Java sort list object by date ascending [duplicate]

I’d like to sort list of my objects by one argument it’s date in format «YYYY-MM-DD HH:mm» by ascending order. I can’t find a right solution. In python It’s easily to sort it using lambda, but in Java I’ve a problem with it.

5 Answers 5

public boolean before(Date when)

true if and only if the instant of time represented by this Date object is strictly earlier than the instant represented by when; false otherwise.

Or you can use after method from Date Class inplace of before

package com.stackoverflow.DataSortReverse; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; class Car < private String name; private Date date; public String getName() < return name; >public void setName(String name) < this.name = name; >public Date getDate() < return date; >public void setDate(Date date) < this.date = date; >public Car(String name, Date date) < super(); this.name = name; this.date = date; >@Override public String toString() < return "Car [date=" + date + "]"; >> public class DateSort < public static void main(String[] args) < SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); ListcarList = new ArrayList(); try < carList.add(new Car("car1",dateFormat.parse("2017-01-10"))); carList.add(new Car("car1",dateFormat.parse("2017-02-10"))); carList.add(new Car("car1",dateFormat.parse("2017-02-30"))); carList.add(new Car("car1",dateFormat.parse("2017-01-09"))); >catch (ParseException e) < System.out.println(e.getMessage()); >/* * if you wish to change sorting order just * replace -1 with 1 and 1 with -1 * * * date1.before(date2) returns true when date1 comes before date2 * in calendar * * java docs :: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#before-java.util.Date- * */ Collections.sort(carList, new Comparator() < @Override public int compare(Car o1, Car o2) < if(o1.getDate().before(o2.getDate()))< return -1; >return 1; > >); System.out.println(carList); > > 

Источник

Читайте также:  Etc php fpm d www conf

Sorting Objects in a List by Date

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

1. Overview

In this tutorial, we’ll discuss sorting objects in a List by date. Most of the sorting techniques or examples let the user sort a list alphabetically, but in this article, we’ll discuss how to do it with Date objects.

We’ll look at using Java’s Comparator class for custom sorting our lists’ values.

2. Setup

Let’s look at the Employee entity we’ll be using in this article:

public class Employee implements Comparable  < private String name; private Date joiningDate; public Employee(String name, Date joiningDate) < // . >// standard getters and setters >

We can notice that we have implemented a Comparable interface in the Employee class. This interface lets us define a strategy for comparing objects with other objects of the same type. This is used to sort the objects in their natural ordering form or defined by the compareTo() method.

3. Sorting Using Comparable

In Java, natural order refers to how we should sort primitives or objects in an array or collection. The sort() method in java.util.Arrays and java.util.Collections should be consistent and reflect the semantics of equality.

We’ll use this method for comparing the current object and the object passed as an argument:

public class Employee implements Comparable  < // . @Override public boolean equals(Object obj) < return ((Employee) obj).getName().equals(getName()); >@Override public int compareTo(Employee employee) < return getJoiningDate().compareTo(employee.getJoiningDate()); >>

This compareTo() method will be comparing the current object with the object that is being sent as a parameter. In the above example, we compare the joining date of the current object with the passed Employee object.

3.1. Sorting in Ascending Order

In most cases, the compareTo() method describes the logic for comparison among objects with natural sorting. Here, we compare the employee’s joining date field with other objects of the same type. Any two employees will return 0 if they have the same joining date:

@Test public void givenEmpList_SortEmpList_thenSortedListinNaturalOrder()

Now, the Collections.sort(employees) will sort the employee list based on its joiningDate instead of its primary key or name. We can see the list is sorted by joiningDate of the employees – that now becomes a natural order for Employee class:

[(Pearl,Tue Apr 27 23:30:47 IST 2021), (Earl,Sun Feb 27 23:30:47 IST 2022), (Steve,Sun Apr 17 23:30:47 IST 2022), (John,Wed Apr 27 23:30:47 IST 2022)]

3.2. Sorting in Descending Order

The Collections.reverseOrder() method sort the objects but in the reverse order as imposed by the natural ordering. This returns a comparator that will perform the ordering in reverse. It’ll throw a NullPointerException when the object returns null on the comparison:

@Test public void givenEmpList_SortEmpList_thenSortedListinDescOrder()

4. Sorting Using Comparator

4.1. Sorting in Ascending Order

Let’s now use the Comparator interface implementation to sort our employee list. Here, we’ll pass an anonymous inner class parameter on the on-the-fly to the Collections.sort() API:

@Test public void givenEmpList_SortEmpList_thenCheckSortedList() < Collections.sort(employees, new Comparator() < public int compare(Employee o1, Employee o2) < return o1.getJoiningDate().compareTo(o2.getJoiningDate()); >>); assertEquals(employees, employeesSortedByDateAsc); >

We can also replace this syntax with the Java 8 Lambda Syntax that makes our code much smaller, as shown below:

@Test public void givenEmpList_SortEmpList_thenCheckSortedListAscLambda()

The compare(arg1, arg2) method takes two arguments of the generic type and returns an integer. Since it is separated from the class definition, we can define a custom comparison based on different variables and entities. This is useful when we want to define a different custom sort for comparing the argument objects.

4.2. Sorting in Descending Order

We can sort the given Employee list in descending order by reversing the employee object comparison, i.e., comparing Employee2 with Employee1. This will reverse the comparison and thus return the result in descending order:

@Test public void givenEmpList_SortEmpList_thenCheckSortedListDescV1() < Collections.sort(employees, new Comparator() < public int compare(Employee emp1, Employee emp2) < return emp2.getJoiningDate().compareTo(emp1.getJoiningDate()); >>); assertEquals(employees, employeesSortedByDateDesc); >

We can also convert the above method to more concise forms using the Java 8 Lambda Expressions. This will perform the same functions as the above function, with the only difference that the code contains fewer lines of code in comparison to the above code. Though this also makes the code less readable. While using Comparator, we pass an anonymous inner class on-the-fly for the Collections.sort() API:

@Test public void givenEmpList_SortEmpList_thenCheckSortedListDescLambda() < Collections.sort(employees, (emp1, emp2) ->emp2.getJoiningDate().compareTo(emp1.getJoiningDate())); assertEquals(employees, employeesSortedByDateDesc); >

5. Conclusion

In this article, we explored how to sort a Java Collection by Date object in both ascending and descending modes.

We also briefly saw the Java 8 lambda features that are useful in sorting and help in making the code concise.

As always, the complete code examples used in this article can be found over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Sorting list of objects by date property

Constructor and stuff ommitted for brevity. I want to sort a list of these objects by their startdate and then assign the startdate of the next object to the previous object’s enddate. To clarify, I start with a list of these objects:

SomeObject object1 = new SomeObject(LocalDate.parse("2015-01-01"), null); SomeObject object2 = new SomeObject(LocalDate.parse("2014-01-01"), null); SomeObject object3 = new SomeObject(LocalDate.parse("2016-01-01"), null); List list = Arrays.asList(object1, object2, object3); 
for (SomeObject object : list) < System.out.println(object.startDate.toString() + " " + object.endDate.toString() ); >2014-01-01 2015-01-01 2015-01-01 2016-01-01 2016-01-01 null 

Each list will only contain 3 or 4 of these objects at most, but the code might have to process tens of thousands of these lists, so I’m looking for an efficient way to do this.

Somehow the described output doesn’t match the objects added in the code snippet above. There are two objects with endDate=null added but in the desired output there is only one without endDate

@dpr The initial end dates don’t matter, they need to be replaced by the start dates of the next object in the sorted list.

do you know how to use a comparator? I can provide example of using a comparator to sort date list if you’d like.

Possible duplicate of Sort objects in ArrayList by date? and other questions — use your search engine.

4 Answers 4

You can use Collections.sort with a Comparator. In Java 8 with Lambdas it looks like this:

 Collections.sort(list, (x, y) -> x.startDate.compareTo(y.startDate)); for (int i = 0; i

why all of you use Collections.sort instead of list.sort(Comparator.comparing(SomeObject::getStartDate)) (assuming getStartDate -accessor)?

list.sort was only introduced in Java 1.8. Collections.sort is older and better known. Besides that it makes no difference, I think.

As an enhancement to the accepted answer:

Collections.sort(list, Comparator.comparing(SomeObject::getStartDate)); 

As you mentioned that you didn’t really care whether it is startDate or endDate and just order all of them, maybe the following will help you:

List dates = list.stream() .flatMap(s -> Stream.of(s.startDate, s.endDate)) .filter(Objects::nonNull) // maybe. if nulls are required too, then skip that part here. (but also check the sorting variant then); note that I use null now if the last date is reached (check the printing part for that) .distinct() .sorted() // natural order // alternatively: natural order + nulls last // .sorted(Comparator.nullsLast(Comparator.comparing(Function.identity()))) .collect(Collectors.toList()); // printing part: IntStream.range(0, dates.size()) .mapToObj(i -> < String from = Objects.toString(dates.get(i)); String upto = Objects.toString(i < dates.size() - 1 ? dates.get(i + 1) : null); // exchange null with the end date you are expecting return from + " - " + upto; >) .forEach(System.out::println); 

EDIT: There was that endDate set on one of your samples before. as that isn’t the case anymore, here an update how you can set the right date ranges. It’s basically similar to what also Ralf Renz has used in his answer:

list.sort(Comparator.comparing(SomeObject::getStartDate)); IntStream.range(0, list.size() - 1) .forEach(i -> list.get(i).endDate = list.get(i + 1).startDate); // or if you care about performance, just do the same as Ralf did: for (int i = 0; i

Источник

Оцените статью