From 629b6bc7444005915983ae8d86c89c4ae215729e Mon Sep 17 00:00:00 2001 From: Ben Culkin Date: Tue, 26 Jul 2022 20:35:01 -0400 Subject: Restructure a bit --- src/main/java/bjc/esodata/Multimap.java | 44 ++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) (limited to 'src/main/java/bjc/esodata/Multimap.java') diff --git a/src/main/java/bjc/esodata/Multimap.java b/src/main/java/bjc/esodata/Multimap.java index fae872e..e18ed49 100644 --- a/src/main/java/bjc/esodata/Multimap.java +++ b/src/main/java/bjc/esodata/Multimap.java @@ -1,6 +1,9 @@ package bjc.esodata; import java.util.*; +import java.util.Map.Entry; + +import bjc.data.Pair; /** * A map that has support for multiple values for a given key. @@ -14,7 +17,7 @@ import java.util.*; * @param The type of keys in the map. * @param The type of values in the map. */ -public class Multimap { +public class Multimap implements Iterable> { private Map> backing; /** @@ -79,6 +82,17 @@ public class Multimap { else return backing.get(key).values(); } + /** + * Get the single value in the map, if there is one. + * @param key The key to look up + * @return An optional containing the key if it is there once, or empty if it is there either no or more than one times + */ + public Optional getSingle(KeyType key) { + Set set = get(key); + + if (set.size() == 1) return Optional.of(set.iterator().next()); + return Optional.empty(); + } /** * Check if there is at least one value mapped to the given key. * @@ -108,4 +122,32 @@ public class Multimap { return backing.get(key).contains(value) > 0; } + + @Override + public Iterator> iterator() { + return new Iterator<>() { + private Iterator>> mapIter = backing.entrySet().iterator(); + private KeyType currKey; + private Iterator setIter; + + @Override + public boolean hasNext() { + while (setIter == null || !setIter.hasNext()) { + if (!mapIter.hasNext()) return false; + Entry> entry = mapIter.next(); + + currKey = entry.getKey(); + setIter = entry.getValue().setView().iterator(); + } + + return setIter.hasNext(); + } + + @Override + public Pair next() { + if (setIter == null || !setIter.hasNext()) throw new NoSuchElementException(); + return Pair.pair(currKey, setIter.next()) ; + } + }; + } } -- cgit v1.2.3