12

I am using LinkedHashMap. I will always process the first value and that can be deleted (if possible) so that during the next iteration I will again take the same first value from the map to process. What can I use to get the first value.

Oliver Gondža
  • 3,386
  • 4
  • 29
  • 49
PrabhaT
  • 858
  • 3
  • 10
  • 22

3 Answers3

26

You can use this to get the first element key:

 Object key = linkedHashMap.keySet().iterator().next();

then to get the value:

Object value = linkedHashMap.get(key);

and finally to remove that entry:

linkedHashMap.remove(key);
Aequitas
  • 2,205
  • 1
  • 25
  • 51
krock
  • 28,904
  • 13
  • 79
  • 85
4

Use the an Iterator on the value set - e.g.

Map map = new LinkedHashMap();
map.put("A", 1);
map.values().iterator().next();

From your question, it's not clear to me that a map is the best object to use for your current task.

amaidment
  • 6,942
  • 5
  • 52
  • 88
2

If you are going to require the value and key it is best to use the EntrySet.

LinkedHashMap<Integer,String> map = new LinkedHashMap<Integer,String>();
Entry<Integer, String> mapEntry = map.entrySet().iterator().next();
Integer key = mapEntry.getKey();
String value = mapEntry.getValue();
BeCodeMonkey
  • 91
  • 1
  • 6