hotmeatballsoup
hotmeatballsoup

Reputation: 625

Adding Java Dates as keys on maps

Java 8 here, although I'm dealing with java.util.Date, not LocalDate.

I have a situation where I need to create a Map<?,?> where the keys are Dates:

Map<Date, List<Fizz>> fizzesBySpecialDate = new HashMap<>;
List<Fizz> fizzes = getFizzesSomehow();

for (Fizz fizz : fizzes) {

  Buzz buzz = getBuzzFromFizz(fizz);

  if (fizzesBySpecialDate.containsKey(buzz.getSpecialDate())) {

    fizzesBySpecialDate.get(buzz.getSpecialDate()).add(fizz);

  } else {

    final List<Fizz> newGroup = new ArrayList<>();
    newGroup.add(fizz);

    fizzesBySpecialDate.put(buzz.getSpecialDate(), newGroup);

  }

}

So my intention is for all Fizzes who have a Buzz with the same specialDate (e.g. 7/4/2019) to be mapped together. However, since each getBuzzFromFizz() will return a Buzz with a new Date instance, none of the Dates will be the same instance, and so I don't believe the above will work.

What I need is a way to say: "Does this map already contain the same String date as the new String date of this current Buzz?". Any ideas how I can accomplish this?

Upvotes: 0

Views: 87

Answers (1)

Vinay Prajapati
Vinay Prajapati

Reputation: 7546

Change the key from buzz.getSpecialDate() to formatted string date without time. And you will be easily able to group the fizzes.

e.g. Key could be YYYY-MM-dd format Date

You can use DateFormat for same.

Upvotes: 1

Related Questions