mateusz58
7/7/2019 - 8:16 PM

ListSortBasedOnObjectField

Sort a List of Objects by Field in Java

Option 1: Collections.sort() with Comparable

Option 2: Collections.sort() with Comparator

Option 3: List interface sort() [Java 8]

Option 4: Stream interface sorted() [Java 8]

Details of doing that task: https://www.codebyamir.com/blog/sort-list-of-objects-by-field-java

package com.example.demo;

import java.util.Date;

public class User {
  private long id;
  private String email;
  private Date createdOn;

  // other getters and setters omitted

  public Date getCreatedOn() {
    return createdOn;
  }

  public void setCreatedOn(Date createdOn) {
    this.createdOn = createdOn;
  }
}
package com.example.demo;

import java.util.Date;

public class User implements Comparable<User> {
  private long id;
  private String email;
  private Date createdOn;

  // other getters and setters omitted

  public Date getCreatedOn() {
    return createdOn;
  }

  public void setCreatedOn(Date createdOn) {
    this.createdOn = createdOn;
  }

  @Override
  public int compareTo(User u) {
    if (getCreatedOn() == null || u.getCreatedOn() == null) {
      return 0;
    }
    return getCreatedOn().compareTo(u.getCreatedOn());
  }
}

Collections.sort(users);
Collections.reverse(users);
Collections.sort(users, new Comparator<User>() {
  @Override
  public int compare(User u1, User u2) {
    return u1.getCreatedOn().compareTo(u2.getCreatedOn());
  }
});
users.sort(Comparator.comparing(User::getCreatedOn));

//descending

users.sort(Comparator.comparing(User::getCreatedOn).reversed());

//ascending
List<User> sortedUsers = users.stream()
  .sorted(Comparator.comparing(User::getCreatedOn))
  .collect(Collectors.toList());
 //descending
  List<User> sortedUsers = users.stream()
  .sorted(Comparator.comparing(User::getCreatedOn).reversed())
  .collect(Collectors.toList());