Go through and return a Java HashMap in order

2

I have the following HashMap

Map<String, Float>notas = new HashMap<String, Float>();
notas.put("Examen 1", 8.0F);
notas.put("1er trimestre", 9.4F);

and I have the following method to go through it and show it on the screen

@SuppressWarnings("rawtypes")
public void getNotas() {

    Iterator ite = this.notas.entrySet().iterator();

    while(ite.hasNext()) {
        Map.Entry e = (Map.Entry) ite.next();
        System.out.println(e.getKey() + " -> "+e.getValue());

    }
}

The problem I have is that when I print it shows me the quarter first and then the value of the exam 1, my question is if there is any way to show them in the order in which I have been adding them to the HashMap or failing to use any other collection or list that shows them in order as they have been added.

    
asked by bruno Diaz martin 01.11.2017 в 21:45
source

1 answer

5

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 .

    
answered by 01.11.2017 / 22:09
source