0

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?

2
  • comparator methods have convention of return -1, 0 and 1. If method returns 0, it means both objects are equal. Commented Jan 5, 2018 at 10:46
  • how on earth would you sort 'duplicates'? if they are equal, either order is 'sorted' Commented Jan 5, 2018 at 10:53

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Comparator.<Game>comparing(Game::getStartDate)
0

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());

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.