Samuel Georgeszusz
Samuel Georgeszusz

Reputation: 131

Retrieving values from hashmap and adding them to a string

I am basically trying to make a string consisting of all the values in my hashmap.

For example String finalOutcome = "forename=Bob&surname=Marl" and the hashmap would be:

Hashmap<String, String> maps = new Hashmap<String, String>();
maps.put("forename", forename);
maps.put("surname", surname);

My app/program keeps crashing when I am trying to add the values in my hashmap to get the finalOutcome. This is my code, and also how do I do it so that & sign does not come after the last value in the hashmap?? I pass this hashmap into another method in another class as follows:

public addMapValues(Hashmap<String, String> maps){
    for(int i=0; i<maps.size(); i++){
        finalOutcome += maps.get(i) + "&";
    }
}

It's just that bit that is causing me a huge headache and I am sure someone here can fix this almost instantly (yes, I am not good with Java)

Would greatly appreciate some help

Upvotes: 0

Views: 76

Answers (2)

shmosel
shmosel

Reputation: 50776

  1. Use a StringBuilder to concatenate strings in a loop.
  2. Consider Guava's map joiner.
  3. Your code doesn't work because you're trying to lookup values by index instead of by key. Maps aren't indexed. If you want to iterate over the values, you should use Map.entrySet().

Example with Guava:

HashMap<String, String> map = new HashMap<String, String>();
String result = Joiner.on('&').withKeyValueSeparator("=").join(map);

Example with loop:

HashMap<String, String> map = new HashMap<String, String>();
StringBuilder sb = new StringBuilder();
for (Entry<String, String> entry : map.entrySet()) {
    sb.append('&').append(entry.getKey()).append('=').append(entry.getValue());
}
String result = sb.length() > 0 ? sb.substring(1) : "";

Example with Java 8 streams (based on another answer that was deleted from some reason):

HashMap<String, String> map = new HashMap<String, String>();
String result = map.entrySet().stream()
        .map(e -> e.getKey() + "=" + e.getValue())
        .collect(Collectors.joining("&"));

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44854

Consider using a StringBuilder object

StringBuilder finalOutcome  = new StringBuilder  ();

for (String name: maps.values()) {
    finalOutcome.append (name).append("&");
}

return finalOutcome.toString ();

Consider using https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#values() to get the data out of the Map

Also, please be aware that you are using the same key if you are looping i.e. forename, so if you were to add a new person, they would replace the existing person in your map.

Upvotes: 0

Related Questions