In: Computer Science
Write a program which takes three lists of names, and print out all the names only once. The expected runtime should be O(n) where n is the total number of names in the lists. You don’t have to sort the list. Use appropriate data structure to store the names, so add all data to the collection only once efficiently. The read-in list method and list1, list2, list3 is given. You may assume that the expected runtime of searching or inserting into a hash table is O(1). Do not call the list's contains method, because it slows down the run time.
import java.io.*;
import java.util.*;
public class A4PrintName{
public static List<String> readInFile(String filename){
List<String> input = new ArrayList<>();
try (Scanner sin = new Scanner(new FileReader(filename))){
while (sin.hasNextLine()){
input.add(sin.nextLine());
}
} catch (FileNotFoundException e){
e.printStackTrace();
}
return input;
}
public static void main(String[] args){
List<String> namelist1 = readInFile("A4input1.txt");
List<String> namelist2 = readInFile("A4input2.txt");
List<String> namelist3 = readInFile("A4input3.txt");
Set<String> names;
//your code starts here... you may write any function where you need.
}
}
list 1:
Amy Andy Anna Ben Benjamin Catherine Emma James Jessie Jennifer John Karen Kelly Kyle Lena Liam Mary Mia Steve William
list 2:
Amy Andy Anne Ben Benjamin Catherine David Emma James Jessie Jennifer Jenny John Karen Kelly Kyle Mary Mia Selina Tina William
list 3:
Amy Ana Anne Dave George Selina Shawn William
import java.io.*;
import java.util.*;
public class Main{
public static List<String> readInFile(String filename){
List<String> input = new ArrayList<>();
try (Scanner sin = new Scanner(new FileReader(filename))){
while (sin.hasNextLine()){
input.add(sin.nextLine());
}
} catch (FileNotFoundException e){
e.printStackTrace();
}
return input;
}
public static void main(String[] args){
List<String> namelist1 = readInFile("A4input1.txt");
List<String> namelist2 = readInFile("A4input2.txt");
List<String> namelist3 = readInFile("A4input3.txt");
Set<String> names=new
HashSet<String>();//create hashset
names.addAll(namelist1);//add all values using addAll method in
namelist1
names.addAll(namelist2);//in the same manner add for
namelist2,namelist3
names.addAll(namelist3);
System.out.println(names);//print the names
/*You can also use loop upto how many values are there and add each
element separately*/
}
}

If you have any doubts comment it