可以使用Java的集合类进行数据分组和排序。

例如,假设有一个包含学生姓名和分数的数据列表,需要按分数分组并按分数从高到低排序,可以使用如下代码:

import java.util.*;

public class GroupAndSortDemo {
    public static void main(String[] args) {
        // 假设有以下学生分数数据
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("张三", 80));
        studentList.add(new Student("李四", 90));
        studentList.add(new Student("王五", 75));
        studentList.add(new Student("赵六", 85));
        studentList.add(new Student("钱七", 90));
        studentList.add(new Student("孙八", 70));

        // 按分数分组
        Map<Integer, List<Student>> groupMap = new HashMap<>();
        for (Student student : studentList) {
            int score = student.getScore();
            if (!groupMap.containsKey(score)) {
                groupMap.put(score, new ArrayList<>());
            }
            groupMap.get(score).add(student);
        }

        // 按分数从高到低排序
        List<Integer> scoreList = new ArrayList<>(groupMap.keySet());
        Collections.sort(scoreList, Collections.reverseOrder());

        // 输出结果
        for (int score : scoreList) {
            System.out.println("分数为" + score + "的学生有:");
            List<Student> students = groupMap.get(score);
            for (Student student : students) {
                System.out.println(student.getName());
            }
        }
    }

    static class Student {
        private String name;
        private int score;

        public Student(String name, int score) {
            this.name = name;
            this.score = score;
        }

        public String getName() {
            return name;
        }

        public int getScore() {
            return score;
        }
    }
}

输出结果为:

分数为90的学生有:
李四
钱七
分数为85的学生有:
赵六
分数为80的学生有:
张三
分数为75的学生有:
王五
分数为70的学生有:
孙八

首先使用HashMap将学生分数分组,然后使用Collections.sort对分数进行排序,最后输出结果

java 数据分组并排序

原文地址: https://www.cveoy.top/t/topic/c89n 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录