Sort a Map by values

I am relatively new to Java, and often find that I need to sort a Map<Key, Value> on the values. Since the values are not unique, I find myself converting the keySet into an array, and sorting that array through array sort with a custom comparator that sorts on the value associated with the key. … Read more

Collections.emptyMap() vs new HashMap()

From Effective Java, Item #43 – “Return empty arrays or collections, not null” demonstrates returning an empty collection and perhaps even demonstrates using these emptyList(), emptySet(), and emptyMap() methods on the Collections class to get an empty collection that also has the additional benefit of being immutable. From Item #15 “Minimize Mutability”. From Collections-emptySet-Collections-emptyList-Collections Its a type of programming idiom. This is for people that do not … Read more

Create a List of primitive int?

In Java the type of any variable is either a primitive type or a reference type. Generic type arguments must be reference types. Since primitives do not extend Object they cannot be used as generic type arguments for a parametrized type. Instead use the Integer class which is a wrapper for int: If your using Java 7 you can simplify … Read more

HashSet vs. ArrayList

When its comes to the behavior of ArrayList and HashSet they are completely different classes. ArrayList ArrayList Does not validate duplicates. get() is O(1) contains() is O(n) but you have fully control over the order of the entries. get add contains next remove(0) iterator.remove ArrayList O(1) O(1) O(n) O(1) O(1) O(1) Not thread safe and to make it thread safe you have to use Collections.synchronizedList(…) HashSet … Read more