Question

I have a static map like this

static Map<String, Desttination> myMap = new HashMap<String, Desttination>();

Thais have 4 or n key value pair inserted. ....

My requirement is each time when i want to retrieve value from map one by one. For example

When I cal first time like getValue() it return the Value for Key1

Next time it return the Value for Key2
Next time it return the Value for Key3
Next time it return the Value for Key4

Next time it return the Value for Key1 Again..

What is the best way to implement this ? Is there Java inbuilt function for this ?

Thanks

Was it helpful?

Solution

For your requriement, you can use a Queue. Only things once you populated your Queue, you have to first poll() the value from it and after using the value you need to reinsert the value in Queue by calling add() method.

    Queue<String> testQueue = new LinkedList<String>();

    testQueue.add("first");
    testQueue.add("understand");
    testQueue.add("problem");
    testQueue.add("then Ask");
    String fristValue = testQueue.poll();

    //Use your value;
    System.out.println(fristValue);

        //After you are done using it, resubmit it to the Queue
    testQueue.add(fristValue); 

    String secondValue = testQueue.poll();

    //same way....
    System.out.println(secondValue);

Replace String to your own encapsulated class if your really use key. But considering your question, key is not as important for you.

Anyways if its important, then your encapsulated class would look like below:

 class Entry{
    String key;
    String value;
    .....
   //Relevant methods.
 } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top