如何移除HashMap中用户最初输入的前2个键值对
移除HashMap中最初输入的前2个键值对
原有操作步骤及代码
- 输入2个学生ID-姓名键值对存入HashMap:
for (int j = 0; j < 2; j++) { System.out.print("Enter student ID " + (j + 1) + ": "); id = sc.next(); System.out.print("Enter student name " + (j + 1) + ": "); name = sc.next(); studentList.put(id, name); }
- 移除最后一个输入的键值对:
studentList.remove(id);
- 添加一组用户名-密码键值对:
System.out.println("Enter username: "); username = sc.next(); System.out.println("Enter password: "); password = sc.next(); studentList.put(username, password);
- 再添加3组用户名-密码键值对:
for (int y = 0; y < 3; y++) { System.out.print("Enter username " + (y + 1) + ": "); username = sc.next(); System.out.print("Enter password " + (y + 1) + ": "); password = sc.next(); studentList.put(username, password); }
需求与实现方案
需求:移除用户最初输入的前2个键值对。
实现方案:由于HashMap本身不保证存储顺序,无法直接按输入顺序定位最初的键值对,因此在最初输入2个学生键值对时,同步将对应的键存入ArrayList保存顺序。后续需要移除时,遍历ArrayList中的每个键,调用studentList.remove(key)即可完成最初2个键值对的移除。
内容的提问来源于stack exchange,提问作者bruuh
相关产品推荐
相关产品推荐

