2017-10-18 6 views
-1

私はJavaを初めて使い、モデリングに関する質問があります。forループを使用したメソッドの作成

私は、Carオブジェクトのセットを保持するCarRentalCompanyというクラスを持っています。各Carオブジェクトには、Reservationオブジェクトのセットが関連付けられています。 Carクラスでは、その車のすべての予約をSetとして返すgetAllReservationsというメソッドがあります。各Reservationオブジェクトには、関連付けられたcarRenterがあり、String(名前のみ)として格納されます。したがって、Stringを返すReservationクラスにメソッドgetCarRenterがあります。

以下は、私が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

あなたは周波数マップを構築し、最高のカウントは1を返すようにストリームを使用することができます。

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); 
} 
関連する問題