I need to access an entry of map with a given hash code and then concatenate them into one long string forming a sentence however my Java knowledge is very poor and some of them are located inside of a function or even inside of a function of a function. Can I get some guidance on how to do this thank you.
public static void secondMessage() {
aab();
String Value1 = map.get(97);
aba();
cbc();
cbb();
String Value2 = map.get(3159);
ccc();
}
public static void ccc() {
bab();
bcc();
}
public static void aba() {
map.get(2301506);
}
public static void abb() {
map.get(3540684);
}
public static void aab() {
map.get(-1079530081);
}
public static void baa() {
map.get(3139);
}
public static void bba() {
map.get(98256);
}
public static void cbb() {
map.get(3540684);
}
public static void bcc() {
map.get(-103839003);
}
public static void cbc() {
map.get(-309387644);
}
public static void bab() {
abb();
bba();
baa();
}
}
CodePudding user response:
not void should change to String,try to use StringBuilder to contact Strings.
CodePudding user response:
First of all, if you need to do a lot of string concatenation it's usually better to use StringBuilder
rather than concatenating a bunch of Strings
for performance reasons. StringBuffer
can also be used as well.
The intent of trying to get words out of the map is not clear. For example, the below method will get a word matching the key 3540684 but it won't do anything with it (no assignment happens).
public static void abb() {
map.get(3540684);
}
If you insisted on making a method to return each specific word then the following would be a replacement.
public static String abb() {
return map.get(3540684);
}
Here I assume map
is of type Map<Integer, String>
or an implementing class. Question doesn't explicitly mention the map definition.
Some possible solutions using StringBuilder
are demonstrated below.
public static void main(String[] args) {
var map = new HashMap<Integer, String>();
map.put(66, "Chicken");
map.put(12312, "I");
map.put(432341, "hello");
map.put(834523, "am");
map.put(32451, "Rooster");
map.put(683, "a");
// A method
var sentence1 = new StringBuilder();
addWord(sentence1, 432341, map);
addWord(sentence1, 12312, map);
addWord(sentence1, 834523, map);
addWord(sentence1, 683, map);
addWord(sentence1, 66, map);
System.out.println(sentence1.toString());
// Another way
var sentence2 = generateSentence(map, new int[]{ 432341, 12312, 834523, 683, 66 } );
System.out.println(sentence2);
}
public static void addWord(StringBuilder sb, int hashCode, HashMap<Integer, String> map) {
sb.append(map.get(hashCode));
sb.append("");
}
public static String generateSentence(HashMap<Integer, String> map, int[] hashCodes) {
var sentence = new StringBuilder();
for (var hashCode : hashCodes) {
sentence.append(map.get(hashCode));
sentence.append("");
}
return sentence.toString();
}