java idea中使用Map向容器中查询某一学生信息,如果存在则将该学生信息打印出来并对容器中的5个学生信息依总学分的升序打印出来
时间: 2024-03-27 18:37:48 浏览: 33
好的,针对您的问题,我可以给出以下Java代码实现:
首先,定义一个学生类,包含学生的姓名、学号、年级、总学分等信息。
```java
class Student {
String name;
int id;
int grade;
int credit;
// 构造函数
public Student(String name, int id, int grade, int credit) {
this.name = name;
this.id = id;
this.grade = grade;
this.credit = credit;
}
// getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public int getCredit() {
return credit;
}
public void setCredit(int credit) {
this.credit = credit;
}
}
```
接下来,定义一个比较器类,用于对学生信息按总学分的升序进行排序。
```java
class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.getCredit() - s2.getCredit();
}
}
```
然后,使用HashMap容器存储学生信息,以学号为键,学生对象为值。
```java
Map<Integer, Student> students = new HashMap<>();
```
接下来,使用get方法查询某一学生信息是否存在。
```java
int id = 1001; // 假设要查找学号为1001的学生信息
if (students.containsKey(id)) {
// 学生信息存在,打印学生信息
Student s = students.get(id);
System.out.println("Name: " + s.getName());
System.out.println("ID: " + s.getId());
System.out.println("Grade: " + s.getGrade());
System.out.println("Credit: " + s.getCredit());
}
```
最后,对容器中的5个学生信息依总学分的升序打印出来。
```java
List<Student> list = new ArrayList<>(students.values());
Collections.sort(list, new StudentComparator());
for (int i = 0; i < 5; i++) {
Student s = list.get(i);
System.out.println("Name: " + s.getName());
System.out.println("ID: " + s.getId());
System.out.println("Grade: " + s.getGrade());
System.out.println("Credit: " + s.getCredit());
}
```
以上就是完整的代码实现,您可以根据自己的需求进行修改。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)