Map of collections
I wanted to make Map of Collections in Java, so I can make something like
public void add(K key, V value) {
if (containsKey(key)) {
get(key).add(value);
} else {
Collection c = new Collection();
c.add(value);
put(key, value);
}
}
I've tried to make it with something like
public class CollectionMap<K, C extends Collection<V>> extends HashMap<K, C>
but compiler complains about the <V>
part, and there would still be an issue of making proper new collection.
At the moment, I've made two classes: SetMap that look like this
1: public class SetMap<K, V> extends HashMap<K, Set<V>> {
2:
3: public void add(K key, V value) {
4: if (containsKey(key)) {
5: get(key).add(value);
6: } else {
7: Set<V> list = new HashSet<V>();
8: list.add(value);
9: put(key, list);
10: }
11: }
12:
13: }
and ListMap looks pretty much the same except the line 7 where I make new ArrayList. This sort of duplication is small enough to be tolerable, but question remains is this sort of "nested generics" possible in Java?
EDIT:
As erickson said, solution is in <A, B extends Something<A>>
rather than just <B extends Something<A>>
so code can look something like
public abstract class CollelctionMap<K, V, C extends Collection<V>> extends HashMap<K, C> {
protected abstract C newCollection();
public void add(K key, V value) {
if (containsKey(key)) {
get(key).add(value);
} else {
C c = newCollection();
c.add(value);
put(key, c);
}
}
}
and ListMap and SetMap only provide proper collection
Asked by: Kevin235 | Posted: 28-01-2022
Answer 1
If map
is a Map<K, Collection<V>>
, use the idiom computeIfAbsent(...).add(...)
, like this:
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
Or, for a Set
:
map.computeIfAbsent(key, k -> new HashSet<>()).add(value);
Answered by: Roman935 | Posted: 01-03-2022
Answer 2
If it's an option, you may want to just use the Google Collections API - http://code.google.com/p/google-collections/.
Even if you can't use it, maybe having a look at how they implemented their MultiMaps would help you with your implementation.
Answered by: Lucas950 | Posted: 01-03-2022Answer 3
There is a problem with your code:
Collection c = new Collection();
Cannot be instantiated.
I think the next piece of code will solve your problem:
public class CollectionMap<K, V> extends HashMap<K, Collection<V>> {
...
...
...
public void add(K key, V value) {
if (containsKey(key)) {
get(key).add(value);
} else {
Collection<V> c = new ArrayList<V>();
c.add(value);
super.put(key, c);
}
}
}
Answered by: Thomas415 | Posted: 01-03-2022
Answer 4
Apache Commons Collections also offers a MultiMap, but it's pre-JDK 1-.5, so you'll have no generics safety there. You can wrap it in a Collections.checkedMap(Key.class, Value.class, collection) for run-time safety. If you can use Google's Colelction API, it offers an even slicker MultiMap with all the generics, bells and whistles.
Answered by: John970 | Posted: 01-03-2022Answer 5
If possible use Google's Guava. Guys have done a wonderful job there.
Here is another solution.
abstract class MultiMap<K, V> {
private Map<K, Collection<V>> entries = new LinkedHashMap<K, Collection<V>>();
public void put(K key, V value) {
Collection<V> values = entries.get(key);
if (values == null) {
entries.put(key, values = newValueCollection());
}
values.add(value);
}
// other methods
// ..
abstract Collection<V> newValueCollection();
// Helper methods to create different flavors of MultiMaps
public static <K, V> MultiMap<K, V> newArrayListMultiMap() {
return new MultiMap<K, V>() {
Collection<V> newValueCollection() {
return new ArrayList<V>();
}
};
}
public static <K, V> MultiMap<K, V> newHashSetMultiMap() {
return new MultiMap<K, V>() {
Collection<V> newValueCollection() {
return new HashSet<V>();
}
};
}
}
You can use it like
MultiMap<String, Integer> data = MultiMap.newArrayListMultiMap();
data.put("first", 1);
data.put("first", 2);
data.put("first", 3);
Answered by: Catherine663 | Posted: 01-03-2022
Similar questions
java - How to have 2 collections of the same type in JPA?
I've got 2 entities in JPA: Entry and Comment. Entry contains two collections of Comment objects.
@Entity
public class Entry {
...
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@IndexColumn(base = 1, name = "dnr")
private List<Comment> descriptionComments = new ArrayList<Comment>();
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@IndexCo...
Java Collections API Bug?
I've stumbled upon a bug in the Java Collections API, in Collections.java.
Here’s the code verbatim from the JDK’s source. Just so you know, the JavaDoc version tag reads "1.106, 04/21/06". The method is located in line 638.
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
...
Java Collections (LIFO Structure)
I am looking in the Collections framework of Java for a LIFO Structure (Stack) without any success. Basically I want a really simple stack; my perfect option would be a Deque, but I am in Java 1.5.
I would like not to have to add another class to my structure but I am wondering if that is possible:
Is there any class in the Collections framework (1.5) that does the job?
If not, is t...
collections - Strange behavior of Java's TreeMap put() method
I have the following code, which splits up a Vector into a string vector (to use as a key) and an integer at the end (to use as value).
payoffs.put(new Vector<String>(keyAndOutput.subList(0, keyAndOutput.size() - 1)), Integer.parseInt(keyAndOutput.lastElement()));
The TreeMap in question is constructed using a Comparator with the following method, which imposes a lexicographic, case ...
Removing objects from Java Collections
I have a HashMap (although I guess this question applies to other collections) of objects. From what I understand, when the documentation talks about removing mappings, then it is removing the entry from the hashtable, i.e. not necessarily destroying the actual object. If the only remaining reference to the object is in this table, then will the object get garbage collected?
If I do map.clear()
java - Hibernate: Collections of Collections
This is a problem I keep on running into:
I would like to have hibernate manage a single table that represents a collection of collections. For example:
a Map of Maps
List of Sets
Map of Lists
Example, I would like to be able to represent this:
class OwningClass {
Long entityId;
Map<String, List<Element>> mapOfLists;
}
class Element {
...
collections - Java: Removing a custom object from a Vector
I have MyClass, which stores two integers, and I have a Vector<MyClass> called myVector.
Now, I do this:
...
myVector.add(new MyClass(1,1));
for(MyClass m : myVector)
System.out.println(m);
System.out.println(myVector.size());
myVector.remove(new MyClass(1,1));
for(MyClass m : myVector)
System.out.println(m);
System.out.println(myVector.size());
...
java - Generics and Collections in GWT, Null Pointer
When calling a method that adds an object to a collection in GWT I get a null pointer error. I have no idea why as everything I have done creates a very simple object (only contains a string). Here is the code that calls the function and the function:
public class PlantMenu extends VerticalPanel {
private Collection<PlantData> plantList;
private Collection<PlantData> newPlantData;
...
java - What is the best way to deal with collections (lists or sets) in key-value storage?
I wonder what can be an effective way to add/remove items from a really large list when your storage is memcached-like? Maybe there is some distributed storage with Java interface that deals with this problem well?
Someone may recommend Terracotta. I know about it, but that's not exactly what I need. ;)
What is the most efficient Java Collections library?
How to copy Java Collections list
I have an ArrayList and I want to copy it exactly. I use utility classes when possible on the assumption that someone spent some time making it correct. So naturally, I end up with the Collections class which contains a copy method.
Suppose I have the following:
List<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
List<String> b = ...
collections - Java Ordered Map
In Java, Is there an object that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are in the same order?
So as explanation-by-code, I'm looking for something that behaves like my fictitious OrderedMap:
OrderedMap<Integer, String> om = new OrderedMap<>();
om.put(0, "Zero");
om...
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)