I would like to know the best data structure used in java suitable for the following senario.
There is a key and a value.
And the key is not duplicated,
Each Value should store collection of objects where the values in each object will change frequently.
Thanks.
HashMap should serve your need.
HashMap allows you to store key value pairs as a collection. HashMap does not allow duplicate keys. You can use different collection to be stored as a value in your HashMap. For example to create a map with keys as a String and value as a list, the define it like this:
Map<String, List<String>> = new HashMap<String, List<String>>();
Also there are implementations for such collection called MultiMap i.e map where a key is associated with collection of values. Two popular implemantations of MultiMap are:
Apacha MultiMap
Guava MultiMap
A type of map. You aren't saying much besides "I need a key-value thingy". If you need to iterate the map by insertion order, there is a LinkedHashMap. If you need to iterate the map by ascending or descending key values, there are sorted maps. If the map will be shared by multiple threads a concurrent map will be useful. If there will be billions of items in the list and you don't mind hemorraghing data (say this is a caching algorithm), a WeakHashMap is for you.
If by "key is not duplicated" you mean it is a violation if a key is inserted if it already exists, you have a few options.
Related
I will be processing on a sequence of key-value pairs, and returning them as a Set, or rather, a LinkedHashSet.
I'll be merging the elements with the same keys, and process on the values as I go along.
The output I produce will preserve the sequence of keys in the input.
I can think of 2 alternatives:
1.) Do it all on a LinkedHashMap, and convert the result to a LinkedHasSet-- load the LinkedHashMap to a collection and create a LinkedHashSet out of that collection.
2.) Use a HashMap and a LinkedHashSet.
HashMap is for processing-- to fast-access and update the values,
and LinkedHashSet for maintaining the sequence of keys and ensuring the uniqueness of the keys as i go along.
In the end, read the final values from the HashMap and create another LinkedHashSet, this time for key-value pairs and not just keys, and deliver it.
(1) seems much favourable to (2) to me.
Ideally, I'd look to be able to do it all on a LinkedHashSet--
keep the key-value pairs on a LinkedHashSet, but be able to process its elements by keys only--
to be able to
i.) access the value pairs, and
ii.) maintain the uniqueness of the keys
on the keys and not by key-value pairs. But LinkedHashSet doesn't have that, and there's no other structure
in the APIs to do that.
Am I missing something here?
Are there other option(s)?
Thanks in advance.
Not that sharp on the APIs-- wanna make sure.
How can I have a HashMap with unique keys in Java?
Or even does this make any sense to have unique keys in HashMap or the keys are unique by default?
I am a newbie.
thx
Hash map key is unique. Add duplicate key, then it will be overwritten.
HashMap hm = new HashMap();
hm.put("1", new Integer(1));
hm.put("2", new Integer(2));
hm.put("3", new Integer(3));
hm.put("4", new Integer(4));
hm.put("1", new Integer(5));// value integer 1 is overwritten by 5
By default Hashmap is not synchronized.
The keys are unique in all maps. The difference between the various maps implementations concern the possibility of null keys, the order of iteration and concurrency issues.
Try to look at the Java API for Map which is interface that HashMap implements. The first sentence is:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
HasMap has unique keys. as .keySet() returns Set which has unique members
HashMap is a collection to store (key,value) pairs and According to the documentation of HashMap the keys are always unique.
If you add a key which already exists(collision) in the hashmap, the old value will be replaced.
A generic hashmap is usually implemented as an associative array, so let's say your array has N elements, from 0 to N-1, when you want to add a new (key, value) pair, what it's done behind the scenes is (just conceptually):
index = hash(key) mod N
array[index] = value
So, by construction, a key is mapped to one and one only array entry.
Please note that it's actually a bit more complex than this: I am ignoring on purpose things like collision handling, rehashing, etc, you may have a good general idea here https://en.wikipedia.org/wiki/Hash_table
I need to have a HashMap< Integer, String> which can serve fast operations for retrieving a list of all entries whose keys are in a certain integer range besides, getting values from map based on keys.
What Map implementation is suitable for these needs ?
You are probably looking for a NavigableMap. However, you can't use HashMap to create one, because the map would have to be a SortedMap. Consider using TreeMap instead.
Use a TreeMap, which implements NavigableMap supplying a subMap method returning a view of the map with only keys in your range. To get the values, of course you call values() on the result.
If you have an existing Map whose keys implement Comparable, you can construct a TreeMap from it by calling new TreeMap(existingMap), but it will likely be more efficient to create it as a TreeMap from the start.
TreeMap will provide a sorted list of keys. You would then need to trim the list to get your range of values.
I want to make the following types of objects. This is my higher-level desire that I'd like to figure out in Java:
ListObject(key, String): every key corresponds to a String value; key is a string itself
ListObject(key, String[]): every key corresponds to an array of Strings; key is a string itself
ListObject(key, String, String[]): same deal but with two value fields per key.
How would I make (and use!) objects of this type?
Thanks.
You seem to need some Maps rather than Lists. Check the Javadoc for Map implementations; the most common is HashMap, but there are sorted, concurrent, deterministically iterable implementations etc. available too.
ListObject: every key corresponds to a String value; key is a string itself
Map<String, String>
ListObject: every key corresponds to an array of Strings; key is a string itself
Map<String, String[]>
(or preferably Map<String, List<String>>)
ListObject: same deal but with two value fields per key.
Map<String, UserDefinedClassWithTwoFields>
Map<KeyType,ValueType> which is implemented by HashMap<KeyType, ValueType> and TreeMap<KeyType, ValueType>, among others -- HashMap is unordered and TreeMap is ordered.
Other useful Maps are LinkedHashMap which is like HashMap but iterates in insertion order, and com.google.common.collect.Maps in Guava which has a bunch of utility methods, and com.google.common.collect.ImmutableMap which is an immutable map implementation.
For your key corresponding to an array of strings, you might want to look at a Multimap which is a map with multiple values for a given key.
You could use Map for this purpose.
The general syntax for Map is:
Map<String, SomeObject> = new HashMap<String, SomeObject>();
Now there are four kinds of Maps in java:
HASH MAP - Use this map when you don't care about the order in which elements are displayed when you iterate over the map.
HASH TABLE - Synchronized version of hash map.
LINKED HASH MAP - Use this when you care about the insertion order.
TREE MAP - Use this when you want custom sort order.
Map are used to create associative arrays in Java.
Map for your first example. Each String key is associated to a String value.
Map for your second example. Values are arrays of String.
For your last example, you have to create you own class with two fields: one a String and one a String[]. Then, create a map that associates String to an object of your type.
Java's Map type would most likely do the trick. A Map<KeyType, ValueType> stores key-value pairs, so you would have a Map<String, String>, a Map<String, List<String>>, and a Map<String, SomePairType>.
Map is just an interface: you have to pick an implementation. HashMap and TreeMap are your best bets. Both are good, but TreeMap will only work with comparable key types.
For keys, since String is comparable with other Strings, you could use either map implementation.
Why doesn't Java provide functions to get the key/value pairs in a HashSet like exists in Hashtable? It seems like a real pain to have to iterate over it every time you need to get at something. Or is there an easier way to do this?
HashSet doesn't have key/value pairs. It is a Set of objects and you would use an implementer of Set to ensure that a collection of objects contained no duplicates.
Implementers of Map like HashMap have key/value pairs and provide a get(Object key) method to get the value associated with a key.
Since a Set doesn't contain keys and values, there is no way such a view could be provided.
What would you consider to be the key and what would be the value in a Set?
A Set don't have any key/value pairs, just (unique) values. As you already said you get these values via the Iterator or by returning an array with these values with the toArray() method.
Maybe you are looking for a List instead.