Detecting if a Hashmap with Java Option is empty or not?

I want to find out if HashMapall its values ​​are empty or not. What is the best way to do this, besides having to check the value in each record on 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());
+4
source share
2 answers

Use the Java 8 thread 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 circuits in terminal operations"

This is a terminal short circuit operation.

, , noneMatch allMatch, .

+10

, (, , ), , , , , .

-4

Source: https://habr.com/ru/post/1694748/


All Articles