0

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)); } } 

1 Answer 1

1

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++; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.