java - How to convert HashMap.getKey() to Int -


i have hashmap stores attendance information. want convert key int , check condition.

below code:

import java.util.*;  public class hashclass {      public static void main(string args[]) {          hashmap<integer, string> attendancehashmap = new hashmap<integer, string>();         attendancehashmap.put(1, "john");         attendancehashmap.put(2, "jacob");         attendancehashmap.put(3, "peter");         attendancehashmap.put(4, "clara");         attendancehashmap.put(5, "philip");          for(hashmap.entry m:attendancehashmap.entryset()){             if(integer.valueof((int)m.getkey())<3) break;             system.out.println(m.getkey()+" "+m.getvalue());         }     } } 

i want print this

3 peter 4 clara 5 philip 

i tried these methods:

 - (int)m.getkey() : not working  - integer.valueof((int)m.getkey()) : not working  - integer.valueof(m.getkey()) : not working 

how can achieved ?

you saying:

if(integer.valueof((int)m.getkey())<3) break; 

in other words, if first key encounter happens smaller three, terminate loop, hence print nothing. probably, want use continue instead, process next entry:

for(hashmap.entry m:attendancehashmap.entryset()){     if(integer.valueof((int)m.getkey())<3) continue;     system.out.println(m.getkey()+" "+m.getvalue()); } 

but note type conversions obsolete. add missing type arguments entry:

for(hashmap.entry<integer,string> m:attendancehashmap.entryset()){     if(m.getkey()<3) continue;     system.out.println(m.getkey()+" "+m.getvalue()); } 

but might clearer make print statement conditional instead of using loop control:

for(hashmap.entry<integer,string> m:attendancehashmap.entryset()){     if(m.getkey()>=3) {         system.out.println(m.getkey()+" "+m.getvalue());     } } 

as side note, order of printed entries not guaranteed. if want print entries in insertion order, use linkedhashmap:

hashmap<integer, string> attendancehashmap = new linkedhashmap<>(); attendancehashmap.put(1, "john"); attendancehashmap.put(2, "jacob"); attendancehashmap.put(3, "peter"); attendancehashmap.put(4, "clara"); attendancehashmap.put(5, "philip"); // printing code follows... 

and completeness, java 8 solution:

attendancehashmap.foreach((k,v) -> { if(k>=3) system.out.println(k+" "+v); }); 

Comments