Search code examples
javamenuhashmapjava-17

Create menu using Map but to remove the { } and ", "


I have this menu created :

@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
HashMap<Integer, String> menu = new HashMap<>();

menu.put(1, "Show clients from banks" + "\n");
menu.put(2, "Create new bank" + "\n");
menu.put(3, """
        \t. "Choose a bank from where you want to see the clients:
             A. BNP
             B. ING
             C. KBC
        \s""");
System.out.println(menu);

and I get the output bit as you can see in the output down , there are some { } and ", " that I do not want them, is there other way by using HashMap to create something similar ?

OUTPUT:

{1=Show clients from banks
, 2=Create new bank
, 3=    . "Choose a bank from where you want to see the clients: 
     A. BNP
     B. ING
     C. KBC
 }

Desired OUTPUT - as it will be is i will use sout , but i must use this instead HashMap<Integer, String> menu = new HashMap<>();:

 1=Show clients from banks
 2=Create new bank
 3= . "Choose a bank from where you want to see the clients: 
     A. BNP
     B. ING
     C. KBC
 

Solution

  • You would need to override the toString() for HashMap, that's a bad way to do it. Create your own printMenu() method to iterate yourself. I'd also remove the new lines from your options.

    public void printMenu(Map<Integer, String> menu) {
        for (Entry<Integer, String> entry : menu) {
           System.out.println(String.format("%d) %s", entry.getKey(), entry.getValue()));
        }
    }