Reputation: 1
My hashmap contains a key which is the customers name, and the values are all the ratings for the books rated. I have to calculate the average rating for a given booktitle.
How do I access all of the values (ratings) from the hashmap? Is there a method for doing this?
Here is a piece of my code:
/**
* calculate the average rating by all customers for a named book
* only count positive or negative ratings, not 0 (unrated)
* if the booktitle is not found or their are no ratings then
* return NO_AVERAGE
* @param booktitle String to be rated
* @return double the average of all ratings for this book
*/
public double averageRating(String booktitle)
{
numberOfRatingsPerCustomer/total
}
Upvotes: 0
Views: 1119
Reputation: 1831
Here you go take these below code it will help you out to find your rating problem I have done to find average of Student marks in a class
import java.util.*;
public class QueQue {
public static float getAverage(HashMap<String, ArrayList<Integer>> hm, String name) {
ArrayList<Integer> scores;
scores = hm.get(name);
if (scores == null) {
System.out.println("NOT found");
}
int sum = 0;
for (int x : scores) {
sum += x;
}
return (float) sum / scores.size();
}
public static void main(String[] args) {
HashMap<String, ArrayList<Integer>> hm = new HashMap<>();
hm.put("Peter", new ArrayList<>());
hm.get("Peter").add(10);
hm.get("Peter").add(10);
hm.get("Peter").add(10);
hm.put("Nancy", new ArrayList<>());
hm.get("Nancy").add(7);
hm.get("Nancy").add(8);
hm.get("Nancy").add(8);
hm.put("Lily", new ArrayList<>());
hm.get("Lily").add(9);
hm.get("Lily").add(9);
hm.get("Lily").add(8);
System.out.println("Find the average of the Peter");
float num = getAverage(hm, "Peter");
}
}
Upvotes: 0
Reputation: 9283
Your question makes no sense.
You can't have a map with customerName
to hisRatingOfBook
, and search in it for bookTitle
. You need to go one of 1 ways:
1)
create method public double averageRating()
inside Book
class, and keep there, as field, rating being map with customerName
to hisRatingOfBook
2) Use your method:
public double averageRating(String booktitle)
{
numberOfRatingsPerCustomer/total
}
but make your map something more complex, that will hold customer
, and its rating
(being made from book title + rate)
Upvotes: 0
Reputation: 8401
You need to get the keySet from the HashMap. And then Iterate over the keySet and fetch the values from the HashMap.
Upvotes: 1