Is there aany specific reason you are using a LinkedList?If not a map can make your life a lot easier:
Map<String, List<Book>> bookShelf = new HashMap<String, List<Book>>();
void addBook(Book book) {
String key = book.name + book.author; // For illustration
List<Book> bookList = null;
if (!bookShelf.containsKey(key)) {
bookList = new ArrayList<Book>();
bookShelf.put(key, bookList);
} else {
bookList = bookShelf.get(key);
}
bookList.add(book);
}
double fetchAverage(Book input){
String key = ""/*key logic*/;
List<Book> booklist = bookShelf.get(key);
double avg = 0.0;
for(Book b: booklist){
avg += b.price;
}
return avg/booklist.size();
}
OR
in case of LinkedList:
LinkedList<Book> bookList = new LinkedList<Book>();
double avg = 0.0;
int counter = 0;
for (Book b : bookList) {
if (b.equals(inputBook)) { // must override hashCode() and equals in
// Book and it should be independent of
// price
avg += b.price;
counter++;
}
}
return avg / counter;
You can probably enhance it by keeping the List sorted, so all books with same name and author occure consecutively.
OR
Maintain a temporaryList in case you don't want to override equals:
LinkedList<Book> temporaryBookList = new LinkedList<Book>();
for (Book b : bookList) {
if (b.name.equals(inputBook.name) && b.author.equals(inputBook.author)) {
temporaryBookList.add(b);
}
}
double avg = 0.0;
for(Book b : temporaryBookList){
avg += b.price;
}
return avg / temporaryBookList.size();
Note: prices are in double only for illustration. Use of BigDecimal is encouraged for prices and such.