Array to Hash Ruby

That’s it. The * is called the splat operator. One caveat per @Mike Lewis (in the comments): “Be very careful with this. Ruby expands splats on the stack. If you do this with a large dataset, expect to blow out your stack.” So, for most general use cases this method is great, but use a different method if you … Read more

ConcurrentHashMap and Hashtable in Java

ConcurrentHashMap uses multiple buckets to store data. This avoids read locks and greatly improves performance over a HashTable. Both are thread safe, but there are obvious performance wins with ConcurrentHashMap. When you read from a ConcurrentHashMap using get(), there are no locks, contrary to the HashTable for which all operations are simply synchronized. HashTable was released in old versions of Java whereas ConcurrentHashMap is a java 5+ … Read more

What is the difference between the HashMap and Map objects in Java?

There is no difference between the objects; you have a HashMap<String, Object> in both cases. There is a difference in the interface you have to the object. In the first case, the interface is HashMap<String, Object>, whereas in the second it’s Map<String, Object>. But the underlying object is the same. The advantage to using Map<String, Object> is that you can change the underlying … Read more

HashMap get/put complexity

It depends on many things. It’s usually O(1), with a decent hash which itself is constant time… but you could have a hash which takes a long time to compute, and if there are multiple items in the hash map which return the same hash code, get will have to iterate over them calling equals on each of them to find a match. … Read more

How to sort Map values by key in Java?

Short answer Use a TreeMap. This is precisely what it’s for. If this map is passed to you and you cannot determine the type, then you can do the following: This will iterate across the map in natural order of the keys. Longer answer Technically, you can use anything that implements SortedMap, but except for rare cases … Read more

Sorting HashMap by values

Assuming Java, you could sort hashmap just like this: Just a kick-off example. This way is more useful as it sorts the HashMap and keeps the duplicate values as well.

Java Hashmap: How to get key from value?

If you choose to use the Commons Collections library instead of the standard Java Collections framework, you can achieve this with ease. The BidiMap interface in the Collections library is a bi-directional map, allowing you to map a key to a value (like normal maps), and also to map a value to a key, thus allowing you to perform … Read more