-2

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
 
  • 4
    Just don't use HashMap's `toString()`; iterate through the map and format the data any way you want. – David Conrad Feb 08 '22 at 17:26
  • 1
    Thanks for hint , i used this `menu.forEach((key, value) -> System.out.println(key + " - " + value));` that works jsut fine for me :) –  Feb 08 '22 at 17:41
  • 2
    A `HashMap` does not guaranty to retain the order. You need a `LinkedHashMap` to ensure that the iteration order will always match the insertion order. But why are you using a map at all? What’s the supposed advantage over just using a single text block containing the entire output? – Holger Feb 09 '22 at 15:17
  • @Holger , that it was what i should use for the "project" –  Feb 09 '22 at 16:11

1 Answers1

1

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()));
    }
}
Ryan
  • 1,762
  • 6
  • 11
  • Thanks for your support m but i will go with `menu.forEach((key, value) -> System.out.println(key + " - " + value));` +1 Accepted –  Feb 08 '22 at 17:44
  • 1
    I like streams for some things, but for readability, I think a good old for loop is enough. – Ryan Feb 08 '22 at 17:52
  • that sounds fear , i do like them ffor that too but in most situation to make it optimal and to have less lines streams are first place for me . :), Thanks again xD –  Feb 08 '22 at 17:54
  • 1
    Speaking of readability, you know that `System.out.println(String.format("%d) %s", …))` is the same as `System.out.printf("%d) %s%n", …)`? – Holger Feb 09 '22 at 15:14