4

I want to find out if the HashMap has all its values empty or not. What is the best way to do it other than having to check the value in every entry in the map?

HashMap<Long, Optional<Long>> aMap = new HashMap<>(); aMap.put(new Long(55), Optional.empty()); aMap.put(new Long(66), Optional.empty()); aMap.put(new Long(77), Optional.empty()); aMap.put(new Long(99), Optional.empty()); 
9
  • 1
    There is no way of doing it other than checking every entry in the map, but there are various ways of doing that. @SotiriosDelimanolis Solution in that link will not work for Optional. Commented Mar 12, 2018 at 1:16
  • @EJP Why wouldn't it? An allMatch with Optional::isPresent? Commented Mar 12, 2018 at 1:17
  • 4
    This seems like a bad use of Optional. A map should just not have values instead of having placeholder "empty" ones. Commented Mar 12, 2018 at 1:40
  • 1
    @chrylis I don't think that's necessary true, if you've ever had a hashmap with a null value, this is probably a better way than checking null. Commented Mar 12, 2018 at 1:43
  • 1
    @chrylis Thanks for this comment. I was originally using 2 lists of equal sizes and was suggested to put them in a map. But i know the fact that the values are going to be always with all entries or all empty. So a map with Optional does not really fit my actual use case, would not have realized this until reading your comment, although it was good learning how to check all empty values:) Commented Mar 12, 2018 at 1:50

2 Answers 2

10

Use java 8 stream's API.

Using allMatch

boolean allEmpty = aMap.values() .stream() .allMatch(opt -> !opt.isPresent()); 

Or using noneMatch

boolean allEmpty = aMap.values() .stream() .noneMatch(Optional::isPresent); 

An important thing to note from the documentation, is that both methods are 'short-circuiting terminal operations'

This is a short-circuiting terminal operation.

This means that the method doesn't need to evaluate the entire stream, when it founds the first match in noneMatch or the first mismatch in allMatch it returns immediatly.

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

Comments

-6

There is no way of doing it other than checking the value in every entry in the map (of course stopping when you find a non-null), but there are various ways of doing that, and no doubt many answers showing how will be posted.

2 Comments

I think this should've been a comment as it doesn't literally answer the question rather direct towards it.
@PankajSinghal Sometimes the answer is just 'no'. There isn't a way to literally answer the question as posed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.