将具有相同值的对象放入数组中

时间:2016-10-18 21:46:37

标签: java arrays parameters

我试图将参数中具有相同值的对象放入数组中。例如,

 Student a = new Student("Abigail", 1, 5);
        Student b = new Student("Benny", 1, 6);
        Student c = new Student("Charles", 1, 10);
        Student d = new Student("Denise", 2, 12);
        Student e = new Student("Eleanor", 2, 9);
        Student f = new Student("Fred", 2, 5); 

对于此代码,1表示总线路由1,2表示总线路由2.我希望具有相同路由的人使用方法在数组中,而不是手动插入数组内的对象。有办法吗?

2 个答案:

答案 0 :(得分:0)

您可以保留MultimapMap<Integer, List<Student>>

private final Map<Integer, List<Student>> buses = new HashMap<>();

public void addStudent(Student s) {
    buses.computeIfAbsent(s.getRoute(), k -> new ArrayList<>()).add(s);
}

这当然假定Student#getRoute返回您提供给构造函数的数字。

答案 1 :(得分:0)

这也应该有效:

import java.util.Arrays;

public class BusRoute {
    public static void main(String[] args) {
        Student a = new Student("Abigail", 1, 5);
        Student b = new Student("Benny", 1, 6);
        Student c = new Student("Charles", 1, 10);
        Student d = new Student("Denise", 2, 12);
        Student e = new Student("Eleanor", 2, 9);
        Student f = new Student("Fred", 2, 5);

        Student[] students = Student.getBusroute(2, a, b, c, d, e, f);
        System.out.print(students);
    }

    static public class Student {
        String name;
        int busRoute;
        int age;
        Student(String name, int busRoute, int age) {
            this.name = name;
            this.busRoute = busRoute;
            this.age = age;
        }

        public int getBusRoute() {
            return busRoute;
        }

        static public Student[] getBusroute(int busRoute, Student ...students) {
            return (Student[])Arrays.stream(students).filter(student -> student.getBusRoute() == busRoute).toArray();
        }
    }
}