-2

Library Class:

Old version printAllItems() method can be used to call printDetails() method for each element stored in the ArrayList:

private ArrayList<LibraryItem> itemList; // it declares an ArrayList of LibraryItem type 

----

public void printAllItems()
{
    System.out.println("Library Item\n");
    for (LibraryItem libraryItem : itemList)
    {
        libraryItem.printDetails();
    }
    System.out.println("\n==================");
    System.out.println("There are " + itemList.size() + " items");
}

New version printAllItems() method can't be used to call printDetails() method for each element stored in the hashMap:

private Map<String, LibraryItem> itemMap; // it declares a HashMap of String and LibraryItem 

----

public void printAllItems()
{  
    // values() can't be used to call printDetails() for each element
    // it instead calls toString() method for each element, which is problematic for later
    System.out.println("Library Item\n-----------------");
    System.out.println(itemMap.values() + "\n");
    System.out.println("\n=================");
    System.out.println("There are " + itemMap.size() + " items");
}

LibraryItem Class:

protected void printDetails() 
{
        String loan = checkLoan(onLoan);
        System.out.println(title + " with item code " + itemCode + " has been borrowed " + timesBorrowed + " times.");
        System.out.println("This item is at present " + loan + " loan and when new cost " + cost + " pence.");
        System.out.println();
}

How can I call the printDetails() in the new version?

The_Liner
  • 63
  • 1
  • 7
  • What is it you're trying to achieve *exactly* because it seems you could just do `itemMap.values().forEach(LibraryItem::printDetails)` but I have the feeling it is not really what you want right? – Yassin Hajaj Apr 05 '21 at 22:01
  • I suggest you learn about `for` and `while` loops. – Code-Apprentice Apr 05 '21 at 22:03

2 Answers2

4

You can use the simple Collection#forEach method that will simply call printDetails on every object of values()

itemMap.values().forEach(LibraryItem::printDetails)
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
0

Presumably you're simply looking for...

for (LibraryItem libraryItem : itemMap.values()) {
    libraryItem.printDetails();
}

The for (T varName : collection) {} construct can be used to loop over any collection; itemMap.values() returns a collection. It's not an ArrayList, but that's fine.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72