-2

I have list of object type of EventCustomDTO. In this DTO there are many field is there. I want to sort based on there value.

I want sort list based on this three field value. 1.passport = true, 2.featured=true, and status of cancel and Unconfirmed are added into last of list.

@ToString
@AllArgsConstructor
@NoArgsConstructor
@Data
public class EventCustomDTO {
      private Long id;
      private String eventName;
      private Boolean passport;
      private Boolean featured;
      private String status;
}

1.I have try below code

Lisi<EventCustomDTO> list = eventRepo.getAllEvents();

list.sort(Comparator.comparing(EventCustomDTO::getPassport).reversed()
.thenComparing(EventCustomDTO::getFeatured)
.thenComparing(EventCustomDTO::getEventStatus));

but it is not working as per my requirement. So anyone have idea about it. How to sort list of data based on property value.

  • 1
    Does this answer your question? [Collections.sort with multiple fields](https://stackoverflow.com/questions/4258700/collections-sort-with-multiple-fields) – Serial Lazer Nov 03 '20 at 11:52

3 Answers3

0

The thenComparing is for nested sorting: when there are objects with equal values, they are then internally sorted by the next property.

What you apparently want is to define your own completely separate sort order:

list.sort(Comparator.comparing(o -> {
    if (Boolean.TRUE.equals(o.getPassport()) {
        return 1;
    } else if (Boolean.FALSE.equals(o.getFeatured()) {
        return 2;
    } else if ("Cancelled".equals(o.getStatus()) {
        return 3;
    } else if ("Unconfirmed".equals(o.getStatus()) {
        return 4;
    } else {
        return 5;
    }
}));
OrangeDog
  • 36,653
  • 12
  • 122
  • 207
0

You could let EventCustomDTO implement Comparable and implement your own logic based on your wished fields.

@ToString
@AllArgsConstructor
@NoArgsConstructor
@Data
public class EventCustomDTO implements Comparable<EventCustomDTO>{
    private Long id;
    private String eventName;
    private Boolean passport;
    private Boolean featured;
    private String status;

    @Override
    public int compareTo(EventCustomDTO o) {
        return 0;
    }
}

You can return negative values if the object shall be sorted in front of the parameter object.

Milgo
  • 2,617
  • 4
  • 22
  • 37
0
Collections.sort(list, (e1, e2) -> {
    if (e1.getPassport() != e2.getPassport()) {
        return e1.getPassport() ? -1 : 1;
    }

    if (e1.getFeatured() != e2.getFeatured()) {
        return e1.getFeatured() ? -1 : 1;
    }

    if (e1.getEventStatus() != e2.getEventStatus()) {
        // Or do you mean the other way around for this one?
        // Then it would be return e1.getEventStatus() ? 1 : -1;
        return e1.getEventStatus() ? -1 : 1;
    }

    return 0;
});

You mean something like this?

IntoVoid
  • 914
  • 4
  • 7