Sar*_*air 2 java foreach hashmap
我有一个存储出勤信息的HashMap.我只想将Key转换为Int并检查条件.
以下是我的代码:
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想像这样打印
3 Peter
4 Clara
5 Philip
Run Code Online (Sandbox Code Playgroud)
我试过这些方法:
- (int)m.getKey() : not working
- Integer.valueOf((int)m.getKey()) : not working
- Integer.valueOf(m.getKey()) : not working
Run Code Online (Sandbox Code Playgroud)
如何实现这一目标?
你是说:
if(Integer.valueOf((int)m.getKey())<3) break;
Run Code Online (Sandbox Code Playgroud)
换句话说,如果您遇到的第一个键恰好小于3,则终止循环,因此不打印任何内容.最有可能的是,您希望使用它continue来处理下一个条目:
for(HashMap.Entry m:attendanceHashMap.entrySet()){
if(Integer.valueOf((int)m.getKey())<3) continue;
System.out.println(m.getKey()+" "+m.getValue());
}
Run Code Online (Sandbox Code Playgroud)
但请注意,类型转换已过时.只需在条目中添加缺少的类型参数:
for(HashMap.Entry<Integer,String> m:attendanceHashMap.entrySet()){
if(m.getKey()<3) continue;
System.out.println(m.getKey()+" "+m.getValue());
}
Run Code Online (Sandbox Code Playgroud)
但是使print语句有条件而不是使用循环控制可能更清楚:
for(HashMap.Entry<Integer,String> m:attendanceHashMap.entrySet()){
if(m.getKey()>=3) {
System.out.println(m.getKey()+" "+m.getValue());
}
}
Run Code Online (Sandbox Code Playgroud)
作为旁注,不保证打印条目的顺序.如果要按插入顺序打印条目,请使用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...
Run Code Online (Sandbox Code Playgroud)
而为了完整起见,Java 8解决方案:
attendanceHashMap.forEach((k,v) -> { if(k>=3) System.out.println(k+" "+v); });
Run Code Online (Sandbox Code Playgroud)