java123999
java123999

Reputation: 7394

How to sort a List of Objects based on duplicate fields?

I have the following Java POJO

public class Game  {

    public Game(){} 

    private String id;

    private String startDate = "";
}

How can I implement functionality that will determine duplicate fields within a list of Game objects?

For example when both Games have the same start date?

I have used comparator before but only when sorting objects, e.g. based on earliest date etc, but can it be used to sort duplicates?

Upvotes: 0

Views: 532

Answers (3)

Tomator
Tomator

Reputation: 81

As long as startDate is private, a comparator might have no access to this field. Well known method equals() could be overwritten but if you want to check object fo different criteria of equality, this won't suffice.

But you may implement a getter that will serve startDate to the comparator. Or you can impement method boolean isSameDateAs(Game other) that will return true for duplicate.

Upvotes: 0

lexicore
lexicore

Reputation: 43671

If you want to find "duplicate" entries, group elements and look for groups with size > 2.

In Java 8 that would be something like:

games
    .stream()
    .collect(Collectors.groupingBy(Game::getStartDate))
    .values()
    .stream()
    .filter(group -> group.size() > 1)
    .map(group -> group.get(0))
    .collect(Collectors.toList());

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191728

comparator ... can it be used to sort duplicates?

Yes. When compareTo returns 0, that groups all equal elements together.

determine duplicate fields within a list of Game objects?

Make a Comparator<Game> that has a comparison condition of

if (game1.startDate.equals(game2.startDate)) return 0;

By the way, you may want to use some type of LocalDateTime object instead of strings. Then you can actually order dates/times

Upvotes: 1

Related Questions