You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java技术问题:如何构建值为List的Map并按GPA排序学生

Solution to Group Students by Course with GPA Sorting

Let's break this down into straightforward steps. First, I'll assume your predefined Student class looks something like this (adjust method names if yours differ):

public class Student {
    private String course;
    private double gpa;
    // Other fields, constructors, and getter/setter methods
    
    public String getCourse() {
        return course;
    }
    
    public double getGpa() {
        return gpa;
    }
}

Step 1: Core Logic Overview

We need to accomplish two key things:

  • Group students by their enrolled course (using course names as map keys)
  • For each course's student list, sort entries from lowest GPA to highest

Step 2: Implement the Method (Java 8+ Stream API)

The cleanest, most concise way to do this uses Java Streams and collectors. Here's the complete method:

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StudentProcessor {
    public Map<String, List<Student>> groupStudentsByCourseSortedByGpa(List<Student> students) {
        return students.stream()
                // Optional: Filter out students with null/empty course names to avoid invalid map keys
                .filter(student -> student.getCourse() != null && !student.getCourse().isBlank())
                // Group by course name, and collect students into a sorted list
                .collect(Collectors.groupingBy(
                        Student::getCourse,
                        // First collect to a list, then sort it by GPA ascending
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                studentList -> studentList.stream()
                                        .sorted((s1, s2) -> Double.compare(s1.getGpa(), s2.getGpa()))
                                        .collect(Collectors.toList())
                        )
                ));
    }
}

Step 3: Key Details Explained

  • Collectors.groupingBy(Student::getCourse): This creates the base map structure, using each student's course name as the key.
  • Collectors.collectingAndThen: This helper lets us first gather all students for a course into a list, then apply a final transformation—here, sorting the list by GPA.
  • Sorting Logic: Double.compare(s1.getGpa(), s2.getGpa()) ensures we sort from lowest to highest GPA. Swap s1 and s2 if you ever need the reverse order.
  • Optional Filter: The filter step removes students with invalid course entries to keep your map clean. Remove it if your data guarantees all students have valid course names.

Step 4: Alternative (Pre-Java 8 Approach)

If you're working with an older Java version, here's a manual, loop-based implementation:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StudentProcessor {
    public Map<String, List<Student>> groupStudentsByCourseSortedByGpa(List<Student> students) {
        Map<String, List<Student>> courseStudentMap = new HashMap<>();
        
        // First, group students by their course
        for (Student student : students) {
            if (student.getCourse() == null || student.getCourse().isBlank()) {
                continue; // Skip invalid courses
            }
            courseStudentMap.computeIfAbsent(student.getCourse(), k -> new ArrayList<>())
                            .add(student);
        }
        
        // Then sort each course's student list by GPA (low to high)
        for (List<Student> studentList : courseStudentMap.values()) {
            studentList.sort((s1, s2) -> Double.compare(s1.getGpa(), s2.getGpa()));
        }
        
        return courseStudentMap;
    }
}

Both approaches will deliver the exact Map<String, List<Student>> you need, with each course's student list sorted by GPA from lowest to highest.

内容的提问来源于stack exchange,提问作者user3208915

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:53:34