Skip to content

Instantly share code, notes, and snippets.

@pilcrow
Created October 19, 2023 14:22
Show Gist options
  • Save pilcrow/55cd59f478689399944270f60b05b732 to your computer and use it in GitHub Desktop.
Save pilcrow/55cd59f478689399944270f60b05b732 to your computer and use it in GitHub Desktop.
MapEntryUtils unroll map entry (java)
/**
* Public Domain
* 2023-10-19 Mike Pomraning, first version
*/
package local;
import java.util.Map;
import java.util.AbstractMap.SimpleEntry;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.stream.Stream;
import java.util.Collection;
public class MapEntryUtils {
/**
* Unroll a possibly multi-value map entry into a stream of single-value map entries.
* { key:[v1, v2] } -> [ {key:v1}, {key:v2} ]
* { key:scalar } -> [ {key:scalar} ]
*
* E.g., myMap.entrySet().stream().flatMap(MapEntryUtils::unroll)...
*/
public static <K> Stream<Map.Entry<K,Object>> unroll(Map.Entry<K,Object> entry) {
//return (entry.getValue() instanceof Collection)
// ? ((Collection<Object>)entry.getValue()).stream().map(value -> new SimpleEntry<>(entry.getKey(), value))
// : Stream.of(entry);
final Stream<Map.Entry<K,Object>> ret;
final Object value = entry.getValue();
if (value instanceof Collection) {
final K key = entry.getKey();
@SuppressWarnings("unchecked") final Collection<Object> values = (Collection<Object>) value;
ret = values
.stream()
.map(val -> new SimpleEntry<>(key, val));
} else {
ret = Stream.of(entry);
}
return ret;
}
public static <K> Stream<SimpleImmutableEntry<K,Object>> unrollImmutable(Map.Entry<K,Object> entry) {
final Stream<SimpleImmutableEntry<K,Object>> ret;
final Object value = entry.getValue();
if (value instanceof Collection) {
final K key = entry.getKey();
@SuppressWarnings("unchecked") final Collection<Object> values = (Collection<Object>) value;
ret = values
.stream()
.map(val -> new SimpleImmutableEntry<>(key, val));
} else {
ret = Stream.of(new SimpleImmutableEntry<>(entry));
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment