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));
}
}
CodePudding user response:
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 ;
}
CodePudding user response:
You can use entrySet() method to get Set
of Map.Entry
object that represents key value pairs. Here is example for that:
Map<String, String> map = new LinkedHashMap<String,String>();
map.put(1, "value 1");
map.put(2, "value 2");
map.put(3, "value 3");
int count = 0;
for (Map.Entry<String,String> entry : map.entrySet()){
if (count >= 2) {
break;
}
System.out.println(entry.getValue());
count ;
}
You can iterate over the first two lelemets as shown in the above using enchanced for loop.