Which collections can I use if I want to put employee details 1)as key value 2) without key value. In both case I want to retrieve data in the order in which they are inserted.Please Help.
For simple List implementations (simple value list storage), you can use the ArrayList class. For Map (key-value storage), use LinkedHashMap. Both of these implementations will preserve insertion order.
LinkedHashMap:
Hash table and linked list implementation of the Map interface, with predictable iteration 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). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)
For Key-Value pair in ordered format: LinkedHashMap
For non - Key-Value pair in ordered format: ArrayList
Related
I want to know that HashMap is give same sequence of key when iterated each time after adding records.
I am using following code
HashMap<String,String> mapObj=new HashMap<String,String>();
mapObj.put("a", "aValue");
mapObj.put("b", "bValue");
mapObj.put("c", "cValue");
for(String key:mapObj.keySet()){
System.out.println(key+" :: "+mapObj.get(key));
}
for(String key:mapObj.keySet()){
System.out.println(key+" :: "+mapObj.get(key));
}
output of following program is
b :: bValue
c :: cValue
a :: aValue
b :: bValue
c :: cValue
a :: aValue
If you don't make any changes to the HashMap between the two iterations, you'll likely see the same iteration order (even though it's not guaranteed), since this is a deterministic data structure. However, adding or removing entries between the two iterations will probably change the iteration order.
If you want to rely on the iteration order, use LinkedHashMap, in which (by default) the keys are iterated in the order they were first added to the Map.
If you want to iterate over the keys in some specific order, you can use TreeMap instead (where the keys are ordered according to their natural ordering or the supplied Comparator).
Hash map accept the object to be stored as an argument and
generate a number that is unique to it.
HashMap uses hashing to store the entries in hashmap, so there is no gurantee those will appear in specific order. If you want your entries from your HashMap ordered, then you will have to sort it or you can use Treemap
HashMap doesn't maintain the order. If you want your elements to be retrieved in order then better to use LinkedHashMap.
Generally it would be little surprising if the iteration order changed for multiple subsequent invocations (assuming the map itself did not change in between). BUT you should not rely on it as API does not make any guarantee for that.
As per doc:
The Map interface provides three collection views, which allow a map's
contents to be viewed as a set of keys, collection of values, or set
of key-value mappings. The order of a map is defined as the order in
which the iterators on the map's collection views return their
elements. Some map implementations, like the TreeMap class, make
specific guarantees as to their order; others, like the HashMap
class, do not.
You can use LinkedHashMap as its entrySetmaintain insertion ordering, as per Java Doc:
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).
TreeMap maintain the natural ordering of keys.
A Red-Black tree based NavigableMap implementation. 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.
I have a HashMap.
It has 100s of millions of observations.
What's the best way to iterate over the elements of the HashMap, in numerical order of the keys?
I considered changing to TreeMap, but did not do that since it may actually increase the load in creating the Map (as TreeMap is O(n), HashMap is O(1)).
With Java 8 you could use something similar to the following:
import static java.util.Comparator.comparing;
map.entrySet().stream()
.sorted(comparing(Entry::getKey))
.forEach(e -> doSomethingWithTheEntry(e));
That will obviously involve sorting the unsorted keys, which will come at a cost. So you need to decide whether you want to pay the cost upfront with a TreeMap or when required and keep using a HashMap.
You can't iterate over a HashMap in order. You'll have to use TreeMap for that. If you use a LinkedHashMap, you can iterate in the order the keys were inserted to the Map, but it's still not what you want (unless you insert the keys in numerical order).
If your insertion order is the same order as your keys, then you could use a LinkedHashMap.
Hash table and linked list implementation of the Map interface, with predictable iteration 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). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)
I have a fixed set of key value pairs with which I am initializing the LinkedHashMap<String, Double>.
Does the insertion order remain the same when I do a
LinkedHashMap.put(existingKey, newValue);
To be precise my question is, when we update a value for a key using the put method, is the order of initial insertion disturbed??
If so 1) why?
2) How can I prevent this to preserve the initial order of insertion?
I chose LinkedHashMap because, I wanted a collection that supports a key value pair and maintains the the insertion order.
TIA
From the class doc:
Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)
This linked list defines the iteration ordering, which is normally
the order in which keys were inserted into the map (insertion-order).
So, yes, keySet(), values(), and entrySet() (the three collection views mentioned) return values in the order the internal linked list uses. And yes, the JavaDoc for Map and LinkedHashMap guarantee it.
I can't confirm this in the documentation but if i have a LinkedHashMap and i call keySet() on it and iterate over this set is it guaranteed to iterate in insertion order?
It's specified in the Map documentation:
The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.
That means for LinkedHashMap, all the 3 methods - values(), keySet() and entrySet(), each of them providing 3 different collection views, are guaranteed to iterate in the insertion order.
Yes.
See the docs(that you can not see) here: http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html
Hash table and linked list implementation of the Map interface, with
predictable iteration 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). Note that insertion order is not affected if a key
is re-inserted into the map. (A key k is reinserted into a map m if
m.put(k, v) is invoked when m.containsKey(k) would return true
immediately prior to the invocation.)
Let's say I put keys "a", "b", "c" into a TreeMap. How would I use "c" to determine that it was the third element in lexicographic order in the TreeMap?
What is the purpose of the NavigableSet obtained from a TreeMap?
Use LinkedHashMap if you want to retrieve the element in the order in which you insert.
LinkedHashMap
Hash table and linked list implementation of the Map interface, with
predictable iteration 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). Note that insertion order is not affected if a key
is re-inserted into the map. (A key k is reinserted into a map m if
m.put(k, v) is invoked when m.containsKey(k) would return true
immediately prior to the invocation.)
If what you actually want to know is the index of the c key in the sorted set of keys contained in the map, you could simply use
int index = map.headMap("c").size();
Note that it doesn't have anything to do with insertion order, which a TreeMap doesn't maintain.