2017-10-18 53 views
-1

我是Java新手,我有一個建模問題。使用for循環寫入方法

我有一個名爲CarRentalCompany的類,它包含一組Car對象。每個Car對象都關聯一組Reservation對象。在Car類中,我有一個名爲getAllReservations的方法,它將該車的所有保留返回爲Set。每個Reservation對象都有一個carRenter關聯它,存儲爲一個String(只是一個名字)。因此,我在Reservation類中有一個方法getCarRenter,它返回一個String。

下面您可以找到我在CarRentalCompany類中編寫的方法的代碼,該方法通過租用者名稱提供一組Reservation對象。

public Set<Reservation> getReservationsBy(String renter) { 
    Set<Reservation> res = new HashSet<Reservation>(); 
    for(Car c : cars) { 
     for(Reservation r : c.getAllReservations()) { 
      if(r.getCarRenter().equals(renter)) 
       res.add(r); 
     } 
    } 
    return res; 
} 

我現在的問題是:我怎麼能寫在返回與該租賃公司作出的最預訂租車人的名字CarRentalCompany類中的方法?

該方法看起來像這樣:

public String getBestCustomer(){ 
    ?? 
} 
+1

你有什麼已經嘗試過? – Ordous

回答

0

您可以使用流來構建一個頻率圖,並返回一個具有最高計數:

public String getBestCustomer() { 
    return cars.stream() 
      .map(Car::getAllReservations) 
      .flatMap(Set::stream) 
      .collect(Collectors.groupingBy(Reservation::getCarRenter, Collectors.counting())) 
      .entrySet() 
      .max(Map.Entry.comparingByValue()) 
      .map(Map.Entry::getKey) 
      .orElse(null); 
}