What collection should I choose? - java

I need just a collection of two pairs of data, none of them is going to be null. I don't need any sorting or other possibilities. What implementation of Map should I choose?

Map Implementations:
The three general-purpose Map
implementations are HashMap, TreeMap
and LinkedHashMap. If you need
SortedMap operations or key-ordered
Collection-view iteration, use
TreeMap; if you want maximum speed and
don't care about iteration order, use
HashMap; if you want near-HashMap
performance and insertion-order
iteration, use LinkedHashMap. In this
respect, the situation for Map is
analogous to Set. Likewise, everything
else in the Set Implementations
section also applies to Map
implementations

HashMap is usually the default choice. It gives one O(1) lookup.

HashMap is most commonly used for such Key-Value pairs.

Related

Should I use LinkedHashMap or TreeMap if I insert and access in order?

If i put and iterate in natural order, should I use LinkedHashMap or TreeMap?
I will use a Map<int, MyObj>, and I will put them in natural order (1,2,3,...).
I know about their big-O time performances, but I also know that this is a borderline use.
Use a TreeMap. Not for any performance reasons, but because it can be assigned to SortedMap (or NavigableMap), and that communicates clearly your intent that the map has a defined order.
If you want to keep the entries in the order in which you originally insert them, use LinkedHashMap.
If you want the entries kept in a sorted order, use a NavigableMap, the successor to SortedMap. Java comes with two such implementations: TreeMap and ConcurrentHashMap. The latter is thread-safe.
The sorted maps by default use natural order. Optionally, you can provide a Comparator to use for sorting. This has been covered many times already on Stack Overflow, so search to learn more.

Map - Fixed iteration order

Can we get data from a Map in some sequence or ordering which will be fixed for every time in Java?
Well in some maps you can. For example, any implementation of SortedMap (e.g. TreeMap) will return the entries sorted by key order (possibly according to a custom comparator) - although that has implications on the complexity of adding and fetching entries, of course.
Then there's LinkedHashMap which will always return entries in insertion order.
If you're talking about plain HashMap though - no, you mustn't rely on the ordering.
You can use the LinkedHashMap which is an ordered implementation of the Map interface.

java concurrent map sorted by value

I'm looking for a way to have a concurrent map or similar key->value storage that can be sorted by value and not by key.
So far I was looking at ConcurrentSkipListMap but I couldn't find a way to sort it by value (using Comparator), since compare method receives only the keys as parameters.
The map has keys as String and values as Integer. What I'm looking is a way to retrieve the key with the smallest value(integer).
I was also thinking about using 2 maps, and create a separate map with Integer keys and String values and in this way I will have a sorted map by integer as I wanted, however there can be more than one integers with the same value, which could lead me into more problems.
Example
"user1"=>3
"user2"=>1
"user3"=>3
sorted list:
"user2"=>1
"user1"=>3
"user3"=>3
Is there a way to do this or are any 3rd party libraries that can do this?
Thanks
To sort by value where you can have multiple "value" to "key" mapping, you need a MultiMap. This needs to be synchronized as there is no concurrent version.
This doesn't meant the performance will be poor as that depends on how often you call this data structure. e.g. it could add up to 1 micro-second.
I recently had to do this and ended up using a ConcurrentSkipListMap where the keys contain a string and an integer. I ended up using the answer proposed below. The core insight is that you can structure your code to allow for a duplicate of a key with a different value before removing the previous one.
Atomic way to reorder keys in a ConcurrentSkipListMap / ConcurrentSkipListSet?
The problem was to keep a dynamic set of strings which were associated with integers that could change concurrently from different threads, described below. It sounds very similar to what you wanted to do.
Is there an embeddable Java alternative to Redis?
Here's the code for my implementation:
https://github.com/HarvardEconCS/TurkServer/blob/master/turkserver/src/main/java/edu/harvard/econcs/turkserver/util/UserItemMatcher.java
The principle of a ConcurrentMap is that it can be accessed concurrently - if you want it sorted at any time, performance will suffer significantly as that map would need to be fully synchronized (like a hashtable), resulting in poor throughput.
So I think your best bet is to return a sorted view of your map by putting all elements in an unmodifiable TreeMap for example (although sorting a TreeMap by values needs a bit of tweaking).

How does Java order items in a HashMap or a HashTable?

I was wondering how Java orders items in the Map (HashMap or Hashtable) when they are added. Are the keys ordered by the hashcode, memory reference or by allocation precedence...?
It's because I've noticed same pairs in the Map are not always in the same order
java.util.HashMap is unordered; you can't and shouldn't assume anything beyond that.
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
java.util.LinkedHashMap uses insertion-order.
This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
java.util.TreeMap, a SortedMap, uses either natural or custom ordering of the keys.
The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
First of all: HashMap specifically doesn't provide a stable and/or defined ordering. So anything you observe is simply an implementation detail and you must not depend on it in any way.
Since it is sometimes useful to know the reason for the seemingly random ordering, here's the basic idea:
A HashMap has number of buckets (implemented as an array) in which to store entries.
When an item is added to the map, it is assigned to a buckets based on a value derived of its hashCode and the bucket size of the HashMap. (Note that it's possible that the bucket is already occupied, which is called a collision. That's handled gracefully and correctly, but I'll ignore that handling for the description because it doesn't change the concept).
The perceived ordering of the entires (such as returned by iterating over the Map) depends on the order of the entries in those buckets.
Whenever the size is rehashed (because the map exceeded its fullness threshold), then the number of buckets changes, which means that the position of each element might change, since the bucket position is derived from the number of buckets as well.
HashMap does not sort at all. For a map that sorts by key values you should use TreeMap instead.
From the JavaDocs for TreeMap:
Red-Black tree based implementation of
the SortedMap interface. This class
guarantees that the map will be in
ascending key order, sorted according
to the natural order for the key's
class (see Comparable), or by the
comparator provided at creation time,
depending on which constructor is
used.
From the documentation of HashMap:
This class makes no guarantees as to
the order of the map; in particular,
it does not guarantee that the order
will remain constant over time.
A Map is not an ordered data structure - you should not rely on entries in a HashMap being in a certain order. Some Map implementations such as LinkedHashMap and TreeMap do guarantee a certain order, but HashMap does not.
If you really want to know what happens internally, lookup the source code of HashMap - you can find it in src.zip which should be in your JDK installation directory.
A HashMap has a number of "buckets" in which it stores its entries. Which bucket an entry is stored in is determined by the hash code of the key of the entry. The order in which you see the entries in the HashMap depends on the hash codes of the keys. But don't write programs that rely on entries being in a certain order in a HashMap - the implementation might change in a future version of Java and your program then would not work anymore.
hashmap has a not defined order of the elements
There is no defined ordering in a hash table. Keys are placed into a slot, based on the hash code, but even that isn't a trivial order-by-hash-code.
HashMap stores the values using the unique hash-value generated using a part of the key. This hash-value maps to the address where it is going to be stored. This is how it ensures an access O(1).
LinkedHashmap on the other hand preserves the order in which you added to the map.

What is the difference between a HashMap and a TreeMap? [duplicate]

This question already has answers here:
Difference between HashMap, LinkedHashMap and TreeMap
(17 answers)
Closed 8 years ago.
I started learning Java. When would I use a HashMap over a TreeMap?
TreeMap is an example of a SortedMap, which means that the order of the keys can be sorted, and when iterating over the keys, you can expect that they will be in order.
HashMap on the other hand, makes no such guarantee. Therefore, when iterating over the keys of a HashMap, you can't be sure what order they will be in.
HashMap will be more efficient in general, so use it whenever you don't care about the order of the keys.
HashMap is implemented by Hash Table while TreeMap is implemented by Red-Black tree. The main difference between HashMap and TreeMap actually reflect the main difference between a Hash and a Binary Tree , that is, when iterating, TreeMap guarantee can the key order which is determined by either element's compareTo() method or a comparator set in the TreeMap's constructor.
Take a look at following diagram.
To sum up:
HashMap: Lookup-array structure, based on hashCode(), equals() implementations, O(1) runtime complexity for inserting and searching, unsorted
TreeMap: Tree structure, based on compareTo() implementation, O(log(N)) runtime complexity for inserting and searching, sorted
Taken from: HashMap vs. TreeMap
Use HashMap most of the times but use TreeMap when you need the key to be sorted (when you need to iterate the keys).
I'll talk about the HashMap and TreeMap implementation in Java:
HashMap -- implement basic map interface
implemented by an array of buckets, each bucket is a LinkedList of entries
running time of basic operations: put(), average O(1), worst case O(n), happens when the table is resized; get(), remove(), average O(1)
not synchronized, to synchronize it: Map m = Collections.synchronizedMap(new HashMap(...));
Iteration order of the map is unpredictable.
TreeMap -- implement navigable map interface
implemented by a red-black tree
running time of basic operations: put(), get(), remove(), worst case O(lgn)
not synchronized, to synchronize it: SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
provide ordered iteration. higherKey(), lowerKey() can be used to get the successor and predecessor of a given key.
To sum, the biggest difference between HashMap and TreeMap is that TreeMap implements NavigableMap<K,V>, which provide the feature of ordered iteration. Besides, both HashMap and TreeMap are members of Java Collection framework. You can investigate the source code of Java to know more about their implementations.
You almost always use HashMap, you should only use TreeMap if you need your keys to be in a specific order.
HashMap is used for fast lookup, whereas TreeMap is used for sorted iterations over the map.
Along with sorted key store one another difference is with TreeMap, developer can give (String.CASE_INSENSITIVE_ORDER) with String keys, so then the comparator ignores case of key while performing comparison of keys on map access. This is not possible to give such option with HashMap - it is always case sensitive comparisons in HashMap.

Categories

Resources