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,191
  • 3
  • 24
  • 48
PrabhaT
  • 858
  • 3
  • 9
  • 22

3 Answers3

25

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
  • 1,975
  • 1
  • 21
  • 45
krock
  • 27,848
  • 12
  • 75
  • 84
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,692
  • 4
  • 49
  • 86
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();