Java Print all of my keys and map values

A quick question and its probably the easiest answer, but I need to print a textual representation of my content HashMaps.

My code so far:

public void printAll() {
    Set< String> Names = customersDetails.keySet();
    Collection< CustomerDetails> eachCustomersNames = customersDetails.values();
    for (String eachName : Names) {
        System.out.println(eachName)
    }
    for (CustomerDetails eachCustomer : eachCustomersNames) {
        System.out.println(eachCustomer);
    }
}

But this leads to a list of keys and then to a list of values, but I need every line of text to read something like

Bob [example]

Where Bob is the key and example is the value.

+4
source share
6 answers

If you are using Java 8, you can use lambda syntax .forEach()as follows:

customersDetails.forEach((k,v) -> {
    System.out.println(k + "[" + v + "]");
});

Where kis your key, and vis the value associated with the key k.

+1
source

, :

Set < String> Names = customersDetails.keySet();

for (String eachName: Names) {
    System.out.println(eachName + " [" +  customersDetails.get(eachName).toString() + "]")

}
0

Java 8, , :

for (String eachName : Names) {
    System.out.println(eachName + " [" + customersDetails.get(eachName) + "]");
}
0

:

Map<String, String> customersDetails = new HashMap<>();
for (Map.Entry<String, String> entry : customersDetails.entrySet()) {
    System.out.println(entry.getKey()  + '[' + entry.getValue() + ']');
}

java 8, :

customersDetails.entrySet().forEach((entry) -> {
    System.out.println(entry.getKey()  + '[' + entry.getValue() + ']');
});
0

, ReflectionToStringBuilder. fieldd. .

, . ​​

0

/, , HashMap.toString() ( AbstractMap.toString()).

If you have a class CustomerDetailsthat implements the method toString(), you only need to do:

System.out.println(customerDetails);

And it will print your card in the format you need.

0
source

Source: https://habr.com/ru/post/1676061/


All Articles