java - how to iterate through maps in order [duplicate] - java

This question already has answers here:
Java Class that implements Map and keeps insertion order?
(8 answers)
Closed 6 years ago.
This is the code:
for(String key : mymap.stringPropertyNames()) {
//mycode
}
This works correctly but I noticed I get the values I need in random order, is there a way to loop through the map using a particular order?
EDIT: Mymap is a properties object.

This is because you are using a Map without sorting like HashMap
[...] This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Instead of this, you can use some concrete implementation like:
TreeMap:
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.
LinkedHashMap if you need no duplicates...
Hash table and linked list implementation of the Map interface, with predictable iteration order.

If you want predictable iteration order (insertion order) then use a LinkedHashMap
If you want the elements to be sorted you need to use a TreeMap , in this case the Keys need to implement Comparable interface

Either change the Map implementation into one of the ones that support ordering or sort the keys before iterating over them. I am a bit confused though, normally one gets the keys of a map by the keySet method. I am not familiar with stringPropertyNames but if it is a Map you should be able to do something like (untested code):
List keys = new ArrayList(mymap.keySet())
Collections.sort(keys)
for ( String key : keys ) {
[...]
}

Related

How to have sorted entries in an arbitrary order in Java HashMap [duplicate]

This question already has answers here:
Java Class that implements Map and keeps insertion order?
(8 answers)
Closed 7 years ago.
I'm using a HashMap. When I iterate over the map, the data is returned in (often the same) random order. But the data was inserted in a specific order, and I need to preserve the insertion order. How can I do this?
LinkedHashMap is precisely what you're looking for.
It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.
HashMap is unordered per the second line of the documentation:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Perhaps you can do as aix suggests and use a LinkedHashMap, or another ordered collection. Take a look on javapractices.com's guide on Choosing the right Collection.

What are HashMap and HashSet value's order [duplicate]

This question already has answers here:
Iteration order of HashSet
(9 answers)
Closed 5 years ago.
I was wondering, both HashMap and HashSet do not return values in order?
Please someone clarify.
I am confused and why do you need these two?
In a word - yes. Neither HashMap or HashSet give any guarantee on the order of iteration.
The HashMap API does not define the order of iteration.
However, if you look at the implementation of HashMap, you can deduce that there is a complex transient relationship between the iteration order, the keys' hash values, the order in which the keys were inserted and the size of the hashtable. This relationship gets scrambled if the hashtable resizes itself.
Please refer:
Is the order of values retrieved from a HashMap the insertion order
If you want the values in the order you insert you have to use LinkedHasmap other wise you can use TreeMap where sort by the key. hash does not give any order because it uses the hascode to order values it may vary depend on the object.
A HashMap stores key value pairs. A HashSet is an unordered collection of objects in which each there can be no repeats. Neither are necessarily iterated in order insertion or otherwise. There are ordered implementations but you would not use the standard HashMap or HashSet classes.
Talked about further here
Linked Hash Map does maintain insertion order
HashMap is a implementation of Map interface. Map is a data structure to say that A corresponds to B.
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(new Integer(1), "Test");
In the case above we know that every time that we look for 1, the correspondent is "Test".
Sets are something completely different. Sets ensures that no duplicate object will exists in your collection. HashSet is an implementation of Set interface.
To insert and retrieve something in order you could use LinkedHashMap, LinkedHashSet, ArrayList (implementation of List interface) and others
Wrapping it up:
Map - correspond objects
Set - Ensure unique objects in a collection

Occurred order in the iteration at run-time in a map

In the piece of code similar to
//something before
Iteration<String> iterator = hashMap.keySet().iterator();// HashMap<String, Document>
while(iterator.hasNext()){
System.out.println(iterator.next());
}
//something after
I know that the order of print can be different by the order of insertion of entry key, value; all right.
But if I call this piece in another moment, with re-create the variable hashMap and putting them the equal elements, can the second-moment time print be different from the first-time print?
My question was born by a problem with a web-app: I have a list of String in a JSP, but, after some years, the customer call because the order of the String was different in the morning, but it shows the usual order at the afternoon.
The problem is happened in only one day: the web-app uses the explained piece of code for take a Map and populate an ArrayList.
This ArrayList does'nt any explicit changement of order (no Comparator or similar classes).
I think (hope) that the cause of different order of print derives by a different sequence of iteration in the same HashMap at run-time and I looking for a validation by other people.
In the web, I read that the iteration order by a HashMap changes if the HashMap receives a modification: but what happens if the HashMap remains the same?
Hash map document says HashMap makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
that explains though the hashmap is same it can not guaranatee on order. for Ordered map you can use TreeMap or LinkedHashMap
TreeMap API says 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.
HashMap API documentation states that
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
For a Map that keeps its keys in original insertion order, use LinkedHashMap.
For a Map that keeps its keys in sorted order (either natural order or by you passing a Comparator), use either TreeMap or ConcurrentSkipListMap. If multi-threaded, use the second.
For a Map where the key an enum, use EnumMap if you want the entries ordered by the definition order of the enum's objects.
The other six Map implementations bundled with Java 11 do not promise any order to their entries.
See this graphic table of mine as an overview.
Use a LinkedHashMap instead, to preserve insertion order. From the javadoc: "Hash table and linked list implementation of the Map interface, with predictable iteration order."
If you just want a Map with predictable ordering, then you can also use TreeMap. However, a LinkedHashMap is faster, as seen here: "TreeMap has O(log n) performance for containsKey, get, put, and remove, according to the Javadocs, while LinkedHashMap is O(1) for each."
As Octopus mentioned, HashMap "makes no guarantees as to the order of the map," and you shouldn't use it if order must remain consistent.

How to preserve insertion order in HashMap? [duplicate]

This question already has answers here:
Java Class that implements Map and keeps insertion order?
(8 answers)
Closed 7 years ago.
I'm using a HashMap. When I iterate over the map, the data is returned in (often the same) random order. But the data was inserted in a specific order, and I need to preserve the insertion order. How can I do this?
LinkedHashMap is precisely what you're looking for.
It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.
HashMap is unordered per the second line of the documentation:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Perhaps you can do as aix suggests and use a LinkedHashMap, or another ordered collection. Take a look on javapractices.com's guide on Choosing the right Collection.

Behaviour of LinkedHashMap's keySet() and values() methods [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is the order guaranteed for the return of keySet() of a LinkedHashMap object?
Consider I create a LinkedHashMap, like the following:
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("a", "aa");
map.put("b", "bb");
map.put("c", "cc");
When I call keySet(), does that give me an ordered set? And if I call values(), are these ordered too?
EDIT
Sry, meant ordered, not sorted.
First of all LinkedHashMap is ordered but not sorted. TreeMap is sorted (and hence ordered as well).
That being said you can not expect the output of keySet() and values() to be sorted. Actually the JavaDoc says nothing about the order (as it turns out, the order is guaranteed by JavaDoc: Is the order guaranteed for the return of keys and values from a LinkedHashMap object?) of these collections, however looking at the implementation they should follow the order of underlying Map.
To address recent edit to your question: it is not part of the contract, in fact LinkedHashMap does not even implement keySet() and values() but uses base classes's (HashMap) version. Even though based on the implementation you can see the order is preserved, you should not depend on it if you want your application to be portable.
You don't get a SortedSet or a sorted collection when retrieving the key set or the values. However, the returned implementations use the map's key/value iterators and thus would return the values in the order of insertion, e.g. when being used in a foreach loop.
Thus you get the order as defined by the LinkedHashMap but you can not necessarily consider that to be sorted (and you can't resort those collections either).

Categories