0

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

2 Answers 2

1
  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("&"));
Sign up to request clarification or add additional context in comments.

6 Comments

Mate you are a genius, so I am getting the string BUT it is in the reverse order so it is surname=Marl&forename=Bob. How do I change this order? If this can be done then I can relax for a bit
HashMap does not keep an order. If you want to maintain insertion order, use LinkedHashMap.
@SamuelGeorgeszusz, on a separate note, if you're building a GET request, the parameter order shouldn't matter.
You are a LEGEND mate. It works now. If you don't mind could you please explain the last line `String result = sb.length() > 0 ? sb.substring(1) : ""; Other then that I will upvote as of now :)
@SamuelGeorgeszusz, substring(1) trims the leading & from the result. The length() check is to make sure we don't get an out of bounds exception if the map (and therefore the builder) was empty.
|
0

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.

5 Comments

For some reason I am getting null&null&
I still don't get how to do this :/
see the link. Did you try looking?
@ScaryWombat, you're missing the elephant in the room. See point 3 in my answer.
@shmosel Wombats don't like Elephants - too big.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.