You can use a LinkedHashMap
as you said @ rekiem87
Since according to the documentation :
... This implementation differs from HashMap in that it maintains a list
doubly linked that runs through all its entries.
This linked list defines the iteration order, which normally
is the order in which the keys were inserted in the map (order of
insertion) . Note that the insertion order is not visible
affected if a key is reinserted in 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 before the
invocation).
Keep in mind that from Java 8 you can read your Map's entries just like that and you can use diamond <>
to define your map, without having to put the data type inside:
Map<String, Float>notas = new LinkedHashMap<>();
notas.put("Examen 1", 8.0F);
notas.put("1er trimestre", 9.4F);
notas.entrySet().forEach((entry) -> {
System.out.printf("Llave : %s - Valor: %s %n", entry.getKey(), entry.getValue());
});
Result:
Llave : Examen 1 - Valor: 8.0
Llave : 1er trimestre - Valor: 9.4
The use of a TreeMap
would also be possible, but you should take into account what the documentation about it:
TreeMap
This implementation provides a time cost of registro (n)
guaranteed for operations containsKey
, get
, put
and
remove
The algorithms are adaptations of those in Cormen,
Leiserson and Rivest's Introduction to Algorithms.
The best solution would then be LinkedHashMap
.
If there are still doubts you can consult this interesting answer to the question Difference between HashMap, LinkedHashMap and TreeMap in Stackoverflow in English .