Bob
Bob

Reputation: 51

Java Printing all of my maps keys and values

Quick question and its probably the most simple answer but i need to print a textual representation of my HashMaps contents.

My code so far is:

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 results in the list of keys and then a list of values but i need each line of text to read something like

Bob [example]

Where Bob is the key and example is the value.

Upvotes: 4

Views: 11389

Answers (6)

CraigR8806
CraigR8806

Reputation: 1584

If you're using Java 8, you can take advantage of lambda syntax and .forEach() like so:

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

Where k is your key and v is the value tied to key k.

Upvotes: 3

fps
fps

Reputation: 34460

You don't need to iterate over your keys/values in order to print your map, as the HashMap.toString() method already does this for you very efficiently (actually, it's the AbstractMap.toString() method).

If you have your CustomerDetails class implement the toString() method, then you only need to do:

System.out.println(customerDetails);

And this will print your map in the format you require.

Upvotes: 0

Freiheit
Freiheit

Reputation: 8767

If you start dealing with maps with more complicated types consider using ReflectionToStringBuilder. Internally it uses reflection to build a string of an object and its fieldd. It recurses through the object graph too.

It may not be efficient, but it helps a lot with debugging and printing operations.

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59988

You can print your Map like so :

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

If you are using java 8 you can use :

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

Upvotes: 0

Michael Peacock
Michael Peacock

Reputation: 2104

If you're not using Java 8, simply print both key and value for each key:

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

Upvotes: 0

zakum1
zakum1

Reputation: 1112

Every key maps to just one value, so you can just do this:

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

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

}

Upvotes: 0

Related Questions