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.

Post History

71%
+3 −0
Q&A Map<?, Optional<T>> to Map<?, T>

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() retur...

posted 1mo ago by hkotsubo‭  ·  edited 1mo ago by hkotsubo‭

Answer
#2: Post edited by user avatar hkotsubo‭ · 2024-09-11T18:16:54Z (about 1 month ago)
  • 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:
  • ```java
  • 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:
  • ```java
  • 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());
  • }
  • }
  • ```
  • 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:
  • ```java
  • 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:
  • ```java
  • 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.
#1: Initial revision by user avatar hkotsubo‭ · 2024-09-11T18:01:48Z (about 1 month ago)
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:

```java
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:

```java
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());
    }
}
```