Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select value based on index on linkedhashmap

I have some data on linkedhasmap and i want to call first 2 data on linkedhasmap . how can i get 2 data from linkedhashmap. I just want call value 1 and value 2.

here the code

Map<String, String> map = new LinkedHashMap<String,String>();

    map.put(1, "value 1");
    map.put(2, "value 2");
    map.put(3, "value 3");

    for (Map.Entry<String,String> entry : map.entrySet()){

      for(int i=0; i<3;i++){
              if (entry.getKey().equals(i)){

        System.out.println(entry.getValue(i));

        }
      }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Modify your code like this to get the first two values, LinkedHashMap is ordered and preserves the order of insertion.


int count = 0;
for (Map.Entry<Integer, String> entry : map.entrySet()) {
  if (count == 2) {
    break;
  }
  System.out.println(entry.getValue());
  count++;
}



Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading