使用HashSet集合存储Student类对象:使用迭代器及Lambda表达式对其遍历,根据指定学号删除学生对象Java代码实现
时间: 2023-08-14 13:05:17 浏览: 100
Java HashSet集合存储遍历学生对象代码实例
5星 · 资源好评率100%
以下是Java代码实现:
```java
import java.util.HashSet;
import java.util.Iterator;
public class Student {
private String id;
private String name;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public static void main(String[] args) {
HashSet<Student> students = new HashSet<>();
students.add(new Student("001", "Tom"));
students.add(new Student("002", "Jerry"));
students.add(new Student("003", "Lucy"));
students.add(new Student("004", "Amy"));
// 使用迭代器遍历
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student.getId() + " " + student.getName());
}
// 使用Lambda表达式遍历
students.forEach(student -> System.out.println(student.getId() + " " + student.getName()));
// 根据指定学号删除学生对象
String idToRemove = "002";
students.removeIf(student -> student.getId().equals(idToRemove));
}
}
```
其中,使用迭代器遍历的代码为:
```java
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student.getId() + " " + student.getName());
}
```
使用Lambda表达式遍历的代码为:
```java
students.forEach(student -> System.out.println(student.getId() + " " + student.getName()));
```
根据指定学号删除学生对象的代码为:
```java
String idToRemove = "002";
students.removeIf(student -> student.getId().equals(idToRemove));
```
阅读全文