-1

I am needing to loop over a created hashmap to make a new hashmap and add an integer to it.

Right now I am using Iterators, but it seems that it iterates in no particular order

So if I put this data in my map

map.put(one, alpha)
map.put(two, delta)
map.put(three, gamma)

And then I iterated it based on the order My new hashmap would have:

key: one value: 1
key: two value: 2
key: three value: 3

Right now when I try to run it it comes out like this:

key: two value: 1
key: one value: 2
key: three value: 3
The111
  • 5,757
  • 4
  • 39
  • 55
the133448
  • 75
  • 7
  • 2
    See. `HashMap` doesn't maintain *insertion order*, so what you need is a `LinkedHashMap` *which maintains order*. – TheLostMind Dec 26 '14 at 06:31

2 Answers2

2

If you wish to iterate over the keys in the order they were added to the Map, use LinkedHashMap.

If you wish to iterate over the keys in alphabetical order, use TreeMap.

If you wish to iterate over the keys in some arbitrary order you define yourself, use a TreeMap with a supplied Comparator.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

You will need to sort them by keys or values upon on your needs. The below sample will sort them by keys.

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Main {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();

        map.put("1", "alpha");
        map.put("3", "gamma");
        map.put("2", "delta");


        List<String> list = new ArrayList(map.keySet());
        Collections.sort(list);

        for (String s:list){
            System.out.println(map.get(s));
        }

    }

}
Adil Aliyev
  • 1,159
  • 2
  • 9
  • 22