Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Map<?, Optional<T>> to Map<?, T>

+7
−0

I have a Map with Optional values.

I want to filter it to remove empty values.

Map<K, Optional<T>> input;

Map<K, T> result = input.
// here is some code I'm looking for
                   .collect(Collector.toMap(???));

What is easiest way to achieve it?

All I can think of requires Optional.get and I don't like that IDE warns me about it.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

2 answers

+6
−0

Using Optional as a value in a Map will lead you to unnecessary complexity and confusion — as you can see.

The primary intention of Optional is to serve as a return type, indicating that a value may or may not be present.

To achieve what you are looking for, you need to unwrap the values:

final var result = input.entrySet()
    .stream()
    .filter(it -> it.getValue().isPresent())
    .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().get()));
History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

0 comment threads

+3
−0

Based on the code snippet in the question (which uses collect etc), I'm assuming you want to use streams. I'm also infering that "empty values" means those values for which Optional.isEmpty() returns false (and consequently Optional.isPresent() returns true).

In that case, just create a stream for the map entries, filter the non-empty ones and collect to a new map, by getting the Optional's values:

Map<K, T> result = input
    // get stream of map entries
    .entrySet().stream()
    // check if value is present (which means it's not empty)
    .filter(e -> e.getValue().isPresent()) // alternative: .filter(e -> ! e.getValue().isEmpty())
    // collect to a new map, getting the values from the Optional
    .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get()));

But of course you can also do it without streams, using the traditional loop approach:

Map<K, T> result = new HashMap<>();
for (Map.Entry<K, Optional<T>> entry : input.entrySet()) {
    // value is present (AKA: not empty)
    if (entry.getValue().isPresent()) { // alternative: if (! entry.getValue().isEmpty())
        // add the Optional's value to result
        result.put(entry.getKey(), entry.getValue().get());
    }
}

IMO, the second approach makes it easier to change the Map implementation - if you want a TreeMap instead of a HashMap, for example, just need to change the line Map<K, T> result = new HashMap<>(); to use whatever implementation type you want.

With streams, it's also possible, but not so straighforward. You'd have to change the collector to:

Map<K, T> result = input
  ....
  .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get(), (a, b) -> a, TreeMap::new));

The fourth parameter tells what implementation type we'd like to return. But to use this, we must provide the third parameter, which is used to resolve collisions between values associated with the same key. In this case I'm assuming there will be no collisions (as the question has no indication that such situation can happen), so I'm just returning the first occurrence.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »