Add a main so that you can put some code there to call your functions and make s
ID: 3882684 • Letter: A
Question
Add a main so that you can put some code there to call your functions and make sure they work:
public static void main(String[] args) { /* your testing code goes here */ }
Functions you should add if the functionality is possible. Otherwise add an empty function definition with a comment saying "impossible".
Problem #5
public static HashMap<String, List<String>> buildLastNameToFirstNamesMap(String[] fullNames) {
/* fullNames is an array of entries all in the format "FirstName LastName", a first name and a last name separated by a space. This function should return a map where the keys are the LastNames from the input array and the corresponding value is a list of all the FirstNames that appeared with that LastName in the input array. */
}
** Test input: an empty array; an array containing "Barry White" and "Bob Marley"; an array containing "Barry White", "Bob Marley", and "Betty White".
Explanation / Answer
/* package whatever; // don't place package name! */
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
/* to test ..*/
// add element to the array list and then that will get copied to the fullNames array
ArrayList<String> mylist = new ArrayList<String>();
/*mylist.add("Barry White");
mylist.add("Bob Marley");
mylist.add("Betty White");*/
if(mylist.size() == 0)
empty();
else
{
String[] fullNames = new String[mylist.size()];
int i;
for(i=0;i<mylist.size();i++)
fullNames[i] = mylist.get(i);
HashMap<String, List<String>> map = buildLastNameToFirstNamesMap(fullNames);
System.out.println(map);
}
}
public static HashMap<String, List<String>> buildLastNameToFirstNamesMap(String[] fullNames)
{
int i;
HashMap <String, List<String>> map=new HashMap<>();
for(i=0; i< fullNames.length; i++)
{
// splitting first Name and Last Name
String[] splited = fullNames[i].split(" ");
if(map.containsKey(splited[1])) // searching in map
{
map.get(splited[1]).add(splited[0]);
}
else
{
List<String> temp = new ArrayList<String>();
temp.add(splited[0]);
// insertion in map
map.put(splited[1],temp);
}
}
return map;
}
public static void empty()
{
System.out.println("Impossible");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.