Write code that maps Strings to the Integers which represent the lengths of the Strings.
Create a class with a Map <String, Integer>.
Write one method called addStringToMap() that takes a String parameter and adds an entry to the Map with the String as the key and the length of the String as the value. Note that, if there is already an entry with that String as the key, nothing will happen when you add the entry.
Write a method called printOutMap() that prints out all the entries from the Map.
Main should call addStringToMap() repeatedly to add at least ten Strings, including at least one pair of duplicate Strings (like "John" and "John") and at least one other pair that are not duplicates but have the same length (like "Bob" and "Sue".) The Strings may be hard-coded; you do not need to take user input. Main should then call the printOutMap method.
import java.util.HashMap;
import java.util.Map;
public class Mapp {
Map<String, Integer> hm = new
HashMap<String, Integer>();
public static void main(String[] args) {
Mapp mp=new Mapp();
// calling the method addStringToMap
mp.addStringToMap("hello");
mp.addStringToMap("John");
mp.addStringToMap("Congratulation");
mp.addStringToMap("John");
mp.addStringToMap("Bob");
mp.addStringToMap("Rohit");
mp.addStringToMap("Sue");
mp.addStringToMap("Constructor");
mp.addStringToMap("Friends");
mp.addStringToMap("Helmet");
mp.addStringToMap("Mango");
mp.addStringToMap("MAcculam");
mp.addStringToMap("Salman");
mp.printOutMap();
}
// below method used to print the Map value kye and
string
private void printOutMap() {
for (Map.Entry<String,
Integer> me : hm.entrySet()) {
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
}
}
// below mthod uses to calculate the length of the
string
//and then store the corresponding string
private void addStringToMap(String name) {
// find the length of the
string
int l=name.length();
hm.put(name, l);
}
}
----------------------------------------------
SAMPLE OUTPUT:
Rohit:5
Sue:3
Helmet:6
Bob:3
Constructor:11
Friends:7
Salman:6
John:4
Mango:5
hello:5
MAcculam:8
Congratulation:14
------------------------------
SUMMARY:
I have provided the solution as per your requirement, i hope
you're satisfied with the way i have approached. please dont
hesitate to give me a Like if you like it, i appreciate your like.
If you have any queries you can shoot them any time in comments
section. I will be glad to help you.
Thank you :)
Get Answers For Free
Most questions answered within 1 hours.