I need a collection that behaves something like C++ multimap, but I also need to be able to get elements by a range of keys.
You can look into Google Collections. It has multiple implementations for MultiMap.
There is no built-in multimap collection in Java. To solve this you can map to every key a list of values: Map<String, List<String>>, for example. Otherwise there are third-party libraries with implemented multimaps - here is one of them.
There is a simple hack around creating multimap sortable collections in java...Use the dataset TreeMap and for keys enter key*10^4+counter. This way you are storing duplicate key values in the map (by adding counter they are actually not duplicates, so you can store the in treeMap, but you know not to use the last four digits of the integer key values), however your dataset is being sorted using your original key values. Note that depending how large is your dataset you might want to adjust 10^n to make sure that it is larger then the number of entries in your data.
Related
I have a piece of code that loops through a list and builds up a map containing a date as a key and a value of Pair<BigDecimal, Currency>>. It loops though for every currency. It builds up the map correctly the first loop around but every loop after replaces the data due to sharing a date and therefore a key.
How could I change the logic below to handle building a map sharing a date to prevent different currency's amounts being added together?
Consider using a Multimap from the Guava library.
It will be like a Map<Date, List<Pair>>.
Here is the description from the javadoc:
A collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values:
I need to sort a hash map according to the key.The key is a string(so I need to sort it alphabetically) and the value is an integer.
I was trying to search online and found that tree set automatically sorts it once you put it. Could somebody guide me in the right direction as to how I could convert it into a tree set or maybe even if i could just sort it using a hash map.
Thanks in advance
Since hashmaps are unsorted maps by definition you'd need to use another container for that. Depending on your needs there are several options, some being:
Use a TreeMap instead of a HashMap either temporarily or as a replacement. This would be the best option unless you have to keep the hashmap.
Use a TreeSet to sort the keys, then iterate over the keys and extract the values from the HashMap.
Do the same as in option 2 but fill a new LinkedHashMap during iteration. This will result in a map that returns the values in insert order which happens to be sort order due to use of a sorted set. Note that adding elements to the LinkedHashMap will append any new elements to the end - LinkedHashMap is still ordered by insertion order.
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).
For homework, I have to implement a variety of hash functions in C++ or Java. I'm comfortable working with Java, but haven't used its hash functionality.
I want a hash structure that links colliding keys. Like this:
Is LinkedHashMap the correct choice here? Is it HashMap? Either? Why?
Well, just a regular HashMap links entries that end up in the same bucket (each bucket is really an element in an array of linked lists). A LinkedHashMap also maintains links between entries to preserve the insertion order, but that's not what's happening in your diagram.
HashMap does this.
What LinkedHashMap does is linking the keys in insertion order.
I think the standard HashMap already works this way: it has a number of bins, and elements with colliding hash codes end up in the same bin. You can lookup the source code of HashMap yourself: in your JDK installation directory there is a file src.zip that contains the source code.
LinkedHashMap is just a HashMap combined with a List to keep track of the insertion order of elements in the map. The word "linked" in its name doesn't have anything in particular to do with how elements in one bin are stored.
You may use HashMap
Map<String,ArrayList<Object>> map = new HashMap<String,ArrayList<Object>>();
Instead of object specify the type you need.
The HashMap grants fast random access.
Also there are :
TreeMap - data sorted by key.
LinkedHashMap - data stored in order it is entered to the container.
LinkedHashMap is for creating a iteratable map that with predictable order of the keys. Internally, a HashHap is free to use whatever means it deems fit to handle key collision which may or may not be a linked list. I don't think there is any standard guarantee that the underlaying mechanism for collision buckets to use a linked list in Java but in practice they may.
Is there some sort of data structure in Java that resembles a HashMap that can be sorted by key or value? In PHP you can have associative arrays that are sortable. Is there such a thing in Java?
HashMaps are unsorted almost by definition; a good hash function will produce a seemingly random distribution of the keys.
If you want to use a Map in Java that stores its elements in sorted order, consider looking into TreeMap, which is backed by a sorted binary search tree.
If you want something that can be sorted either by key or by value, you may be looking for a bidirectional map or "bimap." Java doesn't have on in its standard libraries, and the closest implementation I know of is Google's BiMap. However, as Pangea pointed out, it does not support elements in sorted order. You could easily make your own implementation by just using two TreeMaps, though, one from keys to values and one from values to keys.
Hope this helps!
SortedMap sorted only by keys