How to combine scanner and multimap? - java

I have two files and am trying to read each file line by line by using scanner. Also, I would like to combine these two file with the same Key(name) by using multimap in order to combine these two file into one. Here is the script I have so far. Can someone please give me the suggestion? Thank you.
001.csv contains:
David 188 Male doctor A
Jacob 190 Male CEO A+
Sam 175 Male Engineer A-
002.txt contains:
David 80kg US3000
Jacob 70kg US100000
Sam 65kg US80000
Source code:
public class same_test{
public static void main (String[] args) throws FileNotFoundException {
MultiMap multiMap = new MultiValueMap();
Scanner scanner1 = new Scanner(new File("001.csv"));
Scanner scanner2 = new Scanner(new File("002.txt"));
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
String[] array = line.split("\t",2);
String TheName = array[0];
String score = array[1];
multiMap.put(TheName,score);
}
while (scanner2.hasNextLine()) {
String line2 = scanner2.nextLine();
String[] array2 = line2.split("\t",2);
String TheName2 = array2[0];
String rs = array2[1];
multiMap.put(TheName2,rs);
}
Set<String> keys = multiMap.keyset();
for (String key : keys){
System.out.println(key + "\t" + multiMap.get(key) );
}
}
}

Plz share what problem you facing or output you getting.
I run you code, it works for me.
I used MultiHashMap.
public static void main (String[] args) throws FileNotFoundException {
MultiMap multiMap = new MultiHashMap();
Scanner scanner1 = new Scanner(new File("/obp/f1.csv"));
Scanner scanner2 = new Scanner(new File("/obp/f2.csv"));
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
String[] array = line.split("\\s",2);
String TheName = array[0];
String score = array[1];
multiMap.put(TheName,score);
}
while (scanner2.hasNextLine()) {
String line2 = scanner2.nextLine();
String[] array2 = line2.split("\\s",2);
String TheName2 = array2[0];
String rs = array2[1];
multiMap.put(TheName2,rs);
}
Set<String> keys = multiMap.keySet();
for (String key : keys){
System.out.println(key + "\t" + multiMap.get(key) );
}
}
output
David [188 Male doctor A , 80kg US3000 ]
Jacob [190 Male CEO A+ , 70kg US100000 ]
Sam [ 175 Male Engineer A- , 65kg US80000 ]

This answer is limited to the constraint that there is always a unique name like David. i.e. there will be only one David in the both the files.
Use
HashMap<String,Person> personMap = new HashMap<String,Person>();
Person Class will look like
class Person {
String name;
String sex;
int height;
int weight;
}
Note : Mark fields as private along with public setters and getters
Where Person is your POJO class containing all the relevant fields for a person. You will create a new Java POJO instance for every name during the scan of the first file and put an entry of this object mapped with the name. then, in the second scanner loop, you can get the Person object out of the map with the name from the second file (which matches actually) and set the remaining fields in it. On completion of the method, you will get all the details in the form of Person instances mapped with their names

Related

asking about non-primitives arraylist

I have created ArrayList. How can i use this list to get method or attribute from the class. I tried but i could not reach any solution.
I tried to get into element in array list and get some attributes but i can't.
public static void printOptions() {
System.out.println("Welcome to our university!");
System.out.println("Operations:");
System.out.println("1- College");System.out.println("a) Number of Departments");System.out.println("b) Number of Courses");System.out.println("c) Number of Professors");System.out.println("d) Number of Students");System.out.println("e) Report");
System.out.println("2- Department");System.out.println("a) New");System.out.println("b) Number of Courses");System.out.println("c) Number of Students");System.out.println("d) Is Full");System.out.println("e) Enroll");System.out.println("f) Report");
System.out.println("3- Course");System.out.println("a) New");System.out.println("b) Number of Students");System.out.println("c) Assign");System.out.println("d) Is assigned");System.out.println("e) Professor Name");System.out.println("f) Is Full");System.out.println("g) Enroll");System.out.println("h) Report");
System.out.println("4- Professor");System.out.println("a) New");System.out.println("b) Display Salary");System.out.println("c) Get Raise");System.out.println("d) Report");
System.out.println("5- Student");System.out.println("a) New");System.out.println("b) Report");
System.out.println("6- Quit");
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
printOptions() ;
List<Department> departmentList;departmentList = new ArrayList<>();
List<Course> courseList ;courseList = new ArrayList<>();
List<Professor> proffList = new ArrayList<>() ;
List<Student> studentList;studentList = new ArrayList<>() ;
Scanner in = new Scanner(System.in) ;
int d = 0 , c = 0 , p = 0 , s=0 ;
College AinShams = new College() ;
while (true){
String option = in.nextLine() ;
if(!"6".equals(option)) {
if ("2a".equals(option)) { // Define new department
System.out.println("Department Name:");
String depName = in.nextLine() ;
System.out.println("Department Description:");
String depDescripe = in.nextLine() ;
System.out.println("Department Max Students:");
int max_num = in.nextInt() ;
in.nextLine() ;
Department Department_Name = new Department(depName, depDescripe, max_num);
// departmentList.add(Department_Name);
departmentList.add(d, Department_Name);
d++ ;
AinShams.setDepart(departmentList);
}
else if ("4a".equalsIgnoreCase(option)) {//new proff
System.out.println("Professor Firstname:");
String firstName = in.nextLine() ;
System.out.println("Professor Lastname:");
String lastName = in.nextLine();
System.out.println("Professor telephone:");
String telephone = in.nextLine();
System.out.println("Professor address:");
String address = in.nextLine();
System.out.println("Professor salary:");
double salary = in.nextDouble() ;
Professor proff = new Professor(firstName, lastName, telephone, address, salary);
proffList.add(p,proff) ;
p++ ;
AinShams.setProf(proffList);
}
else if ("2e".equalsIgnoreCase(option)) {//add student in department
System.out.println("Department:");
String dep= in.nextLine() ;
System.out.println("Student:");
String stu= in.nextLine();
// System.out.println(AinShams.getDepart());
AinShams.getDepart().
/*for (int i = 0; i < AinShams.getDepart().size(); i++) {
}*/
}
System.out.println("============");
System.out.println("Enter Operation");
System.out.println("============");
}else {break ;}
}
}
}
In condition (2e), I need to get methods and attributes in class which I assigned in array List
AinShams.getDepart() is referring to an object which you defined as data type College:
College AinShams = new College();
The rest of the College code is not in this fragment so I cannot tell whether the .getDepart() method exists. Either way, the College is not an ArrayList.
If you want to reach the methods and fields of objects inside an ArrayList something like the following would work. As an example I take the ArrayList called departmentlist, and use the get() method to return the 0th element from that list. Assuming the 0th element of that class is an object of type Department, the .name asks for the name field (again, assuming this name variable exists in the Department class). The .getName() would be a better way to get the name value but requires you coding this method in the Department class.
departmentlist.get(0).name
departmentlist.get(0).getName()
By the way, consider reducing some of the "System.out.println()" clutter in the top of your code by formatting your output with the "\n" new line key. Try these two examples using 1 system.out.println call to print two lines of text:
System.out.println("Welcome to our university!" + "\n" + "Operations:");
System.out.println("Welcome to our university! \nOperations:");
You want to add a new student to a department. Your College class has other attributes like list of departments, professors, etc.
Approach:
You can get the Department object from the array list, by the department name (property) passed by the user in case-2e. Then use that object to insert new student to its student's list.
Code:
Your code can be something like below (Pardon any compilation error as I haven't used any IDE. Follow the approach):
String dept = in.nextLine();
Department department = AinShams.getDepart().stream().filter(department -> department.getName().contentEquals(dept)).limit(1);
department.getStudentList().add(new Student());
Follow the link for non-stream version:
How to find an object in an ArrayList by property
OR Use the following method:
Department findDepartment(List<Department> deptList, String dept) {
for(Department department : deptList) {
if(department.getName().equals(dept)) {
return department;
}
}
return null;
}

Is there a way loop through 2 arrays and print the element of array 1 if it contains the substring of any element from array 2?

The problem I am trying to solve is how to read lines from a text file and add it to an array. Then sort each element from this new array by the date that is also in each element. I will explain so its easier to understand but will explain what I am doing.
My text file (First column is name, second is Date of birth and last is the date the person died):
sarah jones,1966-12-02,2018-12-04
matt smith,1983-02-03,2020-03-02
john smith,1967-03-04,2017-04-04
I want to sort this file and output it to another file (testing by printing to console at the moment) by sorting it by the date the person died. A way I thought of doing this is to read each line and pass it to an array. Then read each element within the array, split it and then save the date the person died to another array. Then sort the array that has the death dates, loop through both arrays by seeing if the first element of the death date array matches the first element of the first line in the text file, if so then write it to another file. If not then go to the next line.
For example
BufferedReader reader = new BufferedReader(new FileReader("input_text.txt"));
PrintWriter outputStream = new PrintWriter(new FileWriter("output.txt",true));
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> substr_date = new ArrayList<String>();
String currentline = reader.readLine();
while(currentline !=null){
String a_line[] = currentline.split(",");
substr_date.add(a_line[2])
lines.add(currentline);
currentline = reader.readLine();
}
Collections.sort(substr_date);
for(String date : substr_date){
for(String line : lines){
if(line.contains(date)){
System.out.println(line);
}
}
}
I expect the output to be:
john smith,1967-03-04,2017-04-04
sarah jones,1966-12-02,2018-12-04
matt smith,1983-02-03,2020-03-02
The results are initially in order but then some lines are repeated multiple times and then the whole text file in repeated to the console and becomes a mess. I am not sure how to go about doing this. I am new to java and not sure if I asked this question properly either so if you need any more info please ask.
I would create class for objects which you can insert into a list and then define a comparator on this class which you can use to sort.
Here is an example of the class you could define:
static class DeceasedPerson {
String name;
LocalDate birthDate;
LocalDate deathDate;
DeceasedPerson(String name, LocalDate birthDate, LocalDate deathDate) {
this.name = name;
this.birthDate = birthDate;
this.deathDate = deathDate;
}
#Override
public String toString() {
return name + ", " + birthDate + ", " + deathDate;
}
}
Then you could simply load objects based on this class into a list which you sort using a comparator. Here is some sample code you can run with the class defined above:
public static void main(String[] args) {
String input =
"matt smith,1983-02-03,2020-03-02\n" +
"sarah jones,1966-12-02,2018-12-04\n" +
"john smith,1967-03-04,2017-04-04\n";
List<DeceasedPerson> deceasedPersonList = new ArrayList<>();
try (Scanner scanner = new Scanner(input)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] array = line.split(",");
DeceasedPerson deceasedPerson = new DeceasedPerson(array[0],
LocalDate.parse(array[1]), LocalDate.parse(array[2]));
deceasedPersonList.add(deceasedPerson);
}
}
deceasedPersonList.sort(Comparator.comparing(o -> o.deathDate));
deceasedPersonList.forEach(System.out::println);
}
If you run the code above using the DeceasedPerson class you should see on the console the following output:
john smith, 1967-03-04, 2017-04-04
sarah jones, 1966-12-02, 2018-12-04
matt smith, 1983-02-03, 2020-03-02
You could actually also use a TreeSet instead of a List in the main method above and achieve the same results. Here is a move concise alternative:
public static void main(String[] args) {
String input =
"matt smith,1983-02-03,2020-03-02\n" +
"sarah jones,1966-12-02,2018-12-04\n" +
"john smith,1967-03-04,2017-04-04\n";
Set<DeceasedPerson> deceasedPersonList = new TreeSet<>(Comparator.comparing(o -> o.deathDate));
try (Scanner scanner = new Scanner(input)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] array = line.split(",");
DeceasedPerson deceasedPerson = new DeceasedPerson(array[0],
LocalDate.parse(array[1]), LocalDate.parse(array[2]));
deceasedPersonList.add(deceasedPerson);
}
}
deceasedPersonList.forEach(System.out::println);
}
The way you are doing is a long shot. You can do this in much simpler way. You could pass a comparator to the Collections.sort() method like this.
Collections.sort(substr_date, new Comparator<String>{
#Override
public int compare(String str1, String str2){
String dd1 = str1.split(",")[2];
String dd2 = str2.split(",")[2];
return dd1.compareTo(dd2);
}
});
Comparing dates like this, though, is not a good approach. You should convert the date string to LocalDateTime and then use isBefore() or isAfter() to compare them. For ex,
public int compare(String str1, String str2){
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd")
LocalDateTime d1 = LocalDateTime.parse(str1.split(",")[2],format);
LocalDateTime d2 = LocalDateTime.parse(str2.split(",")[2],format);
return d1.isBefore(d2)?-1:(d1.isAfter(d2)?1:0);
}

In Java, how do you loop through a string and check if it contains the keys in a hash map?

The goal is to write a text message abbreviation expander program that takes a string and checks for common abbreviations like LOL, IDK, etc. and replace them with the full length sentence, laugh out loud, I don't know, etc.
import java.util.HashMap;
import java.util.Scanner;
public class TextMsgExpander {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter text: ");
String userInput = scnr.nextLine();
System.out.println("You entered: " + userInput);
// Create new instance of Hash Map
HashMap<String, String> map = new HashMap<String, String>();
//Key value pairs
map.put("LOL", "laugh out loud");
map.put("IDK", "I don't know");
map.put("BFF", "best friend forever");
map.put("TTYL", "talk to you later");
map.put("JK", "just kidding");
map.put("TMI", "too much information");
map.put("IMHO", "in my humble opinion");
//Access points
String LOL = map.get("LOL");
String IDK = map.get("IDK");
String BFF = map.get("BFF");
String TTYL = map.get("TTYL");
String JK = map.get("JK");
String TMI = map.get("TMI");
String IMHO = map.get("IMHO");
System.out.println(TMI);
// While user input contains any of the keys, replace keys with
// values.
return;
}
}
You can instead iterate(loop) over the complete set of keys and look for them in the userInput, if they are present replace them with the respective value from the map as :
for (Map.Entry<String, String> entry : map.entrySet()) {
if (userInput.contains(entry.getKey())) {
userInput = userInput.replaceAll(entry.getKey(), entry.getValue());
}
}
System.out.println("Converted string - " + userInput);

Correct usage of Hashmaps for synonyms

I am trying to store synonyms of a given word into a HashMap. I then take the user input and check to see if it is a word or its synonym. For example, suppose the main word is "bank" and its synonmyns are "safe","tresury" and "credit union". If the user enters "bank", I want to output the word "bank". If the user enters " safe", I still want to output the word "bank" because "safe" is a synonym of "bank".
Here is my Synonymn method
public static void populateSynonymMap() {
HashMap<String, String[]> synonymMap = new HashMap<String, String[]>();
String word = "bank";
String synonymn[] = { "safe", "treasury", "credit union" };
synonymMap.put(word, synonymn);
}
and here is my main method
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
List<String> matches = new ArrayList<String>();
HashMap<String, String[]> synonymMap = new HashMap<String, String[]>();
synonmynMap = populateSynonymMap(); //populate the map
boolean found = false;
Scanner in = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
String input = null;
System.out.println("Welcome To Artifical Intelligence DataBase ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
}
Your synonymMap should be organised other way arround, the key are the "synonyms" and the value is their common output.
So in your example:
String word = "bank";
String synonymn[] = { "safe", "treasury", "credit union" };
for (String syn : synonymn)
synonymMap.put(syn, word);
Then when user enters a word you check if it exists in the synonymMap and if so you return its value:
String syn = synonynMap.get(input);
if (syn != null) return syn;
else return input;
you can add every word of your synonym[] as key to your map too. of course with an array of synonyms containing the word and all other synonyms. i know there have to be better approaches, but thats the easiest way i can think of at the moment

JAVA, Read from a text file, print out info from the array

very new to Java and I have a question
I was given an text file, and asked to find the employee who earn the most, and print out their info (fName, Lname, ID)
the text file was like so:
Date of birth fName lName wage hr work emp ID
12/03/1929 Detzk Fyshe 37 49 07036310484
04/17/1930 Cauus Walden 38 52 63612537553
07/12/1930 Barth Harling 43 72 42101524036
07/16/1930 Bartl Barnhill 43 62 48621748867
I manage to find the max wage. But have no idea how to print out the info
Here my code so far:
public static void main(String[] args) {
File inFile = new File ("dataSet.txt");
ArrayList <String> inData = new ArrayList <String>();
String strline;
try
{
FileInputStream fstream = new FileInputStream(inFile);
BufferedReader br = new BufferedReader (new InputStreamReader (fstream));
while ((strline = br.readLine()) != null)
{
strline = strline.trim();
if ((strline.length()!=0)) inData.add(strline);
}
} catch (Exception e) {
System.err.println("Error CANNOT FIND FILE!");
}
// Max wage finder *start*
int maxWage=0;
for (int i=0; i<inData.size(); i++){
String [] word = inData.get(i).split(" ");
int wage=Integer.parseInt (word[3]);
int hrWork=Integer.parseInt (word[4]);
int earn = wage*hrWork;
if (earn>maxWage){
maxWage=earn;
}
}
System.out.println("Max Wage in $:"+maxWage);
//max wage finder *end*
If you're reading in employee data, then an object-oriented solution to the problem is to create an Employee class with strongly typed (dates as Dates, and integers as ints) attributes that model the contents of the file.
In addition to the instance variables that would store the actual data of each Employee, you might want to override the toString() method in the class so that the employee information can be easily output, for example to System.out. Also, you would need a getter for the "total salary" of an employee (which you calculate with wage * hrWork) so that the salaries of two employees can be compared externally, e.g. by a Comparator.
All in all, the code could look like this for the relevant parts:
private static final DateFormat FORMATTER = new SimpleDateFormat("MM/dd/yyyy");
...
List<Employee> employees = new ArrayList<Employee>();
...
// within the loop that reads the file:
String[] columns = strline.split(" ");
employees.add(new Employee(
FORMATTER.parse(columns[0]), // DOB,
columns[1], // first name
columns[2], // last name
Integer.parseInt(columns[3]), // wage
Integer.parseInt(columns[4]), // hr
columns[5]) // employee id
);
...
// after all lines have been read, output the employee with largest wage
Employee earnsMost = Collections.max(employees, new Comparator<Employee>() {
#Override
public int compare(Employee e1, Employee e2) {
return e1.getTotalSalary() - e2.getTotalSalary();
}
});
System.out.println(earnsMost + " earns most.");

Categories