Sorting a hashmap - java

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.

Related

How to sort HashMap of directories depth first?

I created a hashmap where I store directories as keys and then their contents as values.
When I iterate over the hash map and print everything out I get
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/ek.java
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/nu.java
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/os.java
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/njwqdp/di.html
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/njwqdp/po.html
What I want to get however is
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/njwqdp/di.html
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/njwqdp/po.html
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/ek.java
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/nu.java
files/abknl/bbxudleuf/jlffhq/y/xwjj/ell/os.java
Any ideas?
To come to this I am sorting the hashmaps keys and then print the values of each key
A HashMap is not usually sorted. You will want to use a SortedMap, for example TreeMap. This class will let you use your own Comparator, and thus lets you sort its contents anyway you want it. From the TreeMap(Comparator<? super K>) constructor Javadoc:
Constructs a new, empty tree map, ordered according to the given comparator.
Try using a TreeMap with a suitable Comparator, then putAll entries you have in your HashMap.
If you need to start with a HashMap, you can create a new TreeMap(myHashMap). This will have the same mappings, but will iterate over them in sorted order.

How list differ from map?

In java, List and Map are using in collections. But i couldn't understand at which situations we should use List and which time use Map. What is the major difference between both of them?
Now would be a good time to read the Java collections tutorial - but fundamentally, a list is an ordered sequence of elements which you can access by index, and a map is a usually unordered mapping from keys to values. (Some maps preserve insertion order, but that's implementation-specific.)
It's usually fairly obvious when you want a key/value mapping and when you just want a collection of elements. It becomes less clear if the key is part of the value, but you want to be able to get at an item by that key efficiently. That's still a good use case for a map, even though in some senses you don't have a separate collection of keys.
There's also Set, which is a (usually unordered) collection of distinct elements.
Map is for Key:Value pair kind of data.for instance if you want to map student roll numbers to their names.
List is for simple ordered collection of elements which allow duplicates.
for instance to represent list of student names.
Map Interface
A Map cares about unique identifiers. You map a unique key (the ID) to a specific
value, where both the key and the value are, of course, objects.
The Map implementations let you do things like search for a
value based on the key, ask for a collection of just the values, or ask for a collection
of just the keys. Like Sets, Maps rely on the equals() method to determine whether
two keys are the same or different.
List Interface
A List cares about the index. The one thing that List has that non-lists don't have
is a set of methods related to the index. Those key methods include things like
get(int index), indexOf(Object o), add(int index, Object obj), and so
on. All three List implementations are ordered by index position—a position that
you determine either by setting an object at a specific index or by adding it without
specifying position, in which case the object is added to the end.
list is a linked list, where every object is connected to the next one via pointers. the time it takes to insert a new object to the list is O(1) but the rest of operations on it take longer.
the good thing about it is that it takes exactly the amount of memory you need and not even on byte more than that.
Maps are a data structure that has an array and each entry to the array is calculated with a hashFunction(key) that calculates the location according to the key. almost every operation in a Map taks O(1) (except inserting when there are 2 identical keys) but the space complexity is fairly large.
for more reading try wikipedia's HashMap and linked list
HashList is a data structure storing objects in a hash table and a list.it is a combination of hashmap and doubly linked list. acess will be faster. HashMap is hash table implementation of map interface it is same as HashTable except that it is unsynchronized and allow null values. List is an ordered collection and it allow nulls and duplicates in it. positional acess is possible. Set is a collection that doesn't allow duplicates, it may allow at most one null element. same as our mathematical set.
List is just an ordered collectiom(a sequence). Check this list documentation .You can access elements by their integer index (position in the list), and search for elements in the list.
Also lists allow duplicate elements and multiple NULL elements.
Map is an object that maps the values to the keys. Check this map documentation. A map cannot contain duplicate keys; each key can map to at most one value.
List - This datastructure is used to contain list of elements.
In case you need list of elements and the list may contain duplicate values,
then you have to use List.
Map - It contains data as key value pair. When you have to store data
in key value pair,so that latter you can retrieve data using the key,
you have to use Map data structure.
List implementation - ArrayList, LinkedList
Map implementation - HashMap, TreeMap
In comparison HashMap to ArrayList -
A hash map is the fastest data structure if you want to get all nodes for a page. The list of nodes can be fetched in constant time (O(1)) while with lists the time is O(n) (n=number of pages, faster on sorted lists but never getting near O(1))

Which of Java's hash structures supports 'linear chaining'?

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.

Sortable HashMap-like data structure in Java?

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

Is there a sorted java collection which handles duplicates?

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.

Categories

Resources