使用对象数组查找前10名学生

时间:2017-06-08 11:37:33

标签: arrays sorting

我最近接受了采访,他们问我一个小问题 问题如下

有学生名单

    List<Student> students;

    Class Student{
     String rollNo;
     Map<String, Integer> marks ;
}

Stdunt.marks实际上是主题和标记的组合

应该根据主题编写一个应该返回前十名学生阵列的方法。

List<Student> getTop10(String subjectName){
}

2 个答案:

答案 0 :(得分:0)

我给出的答案是惨淡的

private static void PrintTop5(ArrayList<Student> list,String subject){
    Collections.sort(list, new Comparator<Student>() {

        @Override
        public int compare(Student st1, Student st2) {
            // TODO Auto-generated method stub
            return  st2.getSubjectMark(subject) - st1.getSubjectMark(subject);
        }
    });

    ArrayList<Student> studentList = new ArrayList<Student>(list.subList(0,5));
    for(Student student : studentList){
        System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
    }
}

学生课程如下所示

package com.main;

import java.util.HashMap;

public class Student {

    private String rollNo;
    private HashMap<String, Integer> marks ;

    public Student(){
        marks = new HashMap<>();
    }

    public void setRollNumber(String number){
        this.rollNo = number;
    }

    public void setSubjectAndMark(String subName,int mark){
        this.marks.put(subName, mark);
    }

    public HashMap<String, Integer> getAllMarks(){
        return marks;
    }

    public int getSubjectMark(String subject){
        return marks.get(subject);
    }

    public String getRollNum(){
        return rollNo;
    }
}

答案 1 :(得分:0)

一般来说,你的想法是正确的,要排序整个列表并采取前N名学生,事实上使用java 8它会看起来更干净。

private static void PrintTop5(ArrayList<Student> list,String subject){
    list.sort(Comparator
                    .comparing((Student student) -> student.getSubjectMark(subject))
                    .reversed());

    List<Student> studentList = list.stream().limit(5).collect(Collectors.toList());
    for(Student student : studentList){
        System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
    }
}