2016-10-18 45 views
0

我試圖將參數中具有相同值的對象放到數組中。例如,將參數中具有相同值的對象放到數組中

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表示公共汽車路線之一,和2表示公共汽車路線2.我想用相同的路線的人使用的方法是在陣列中,而不是手動插入的對象內部陣列。有沒有辦法做到這一點?

+0

你知道你到底有多少路線和學生? – ChiefTwoPencils

+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的回報,這個數字你在構造函數中提供。

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(); 
     } 
    } 
} 
相關問題