Search Method for Hashmap - java

I need for Search method for a hashmap and I cant quite figure out how to do it. I'm also trying to do a edit method and I think for this I need the method. My hashMap is to store employee data. I have the MainApp, Employee class and an EmployeeStore class. Can anyone help?
public class MainApp
{
public static void main(String[] args)
{
new MainApp().start();
}
public void start()
{
EmployeeStore Store = new EmployeeStore();
Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));
Store.add(new Employee ("Andy Carroll", 1171,"yahoo.com"));
Store.add(new Employee ("Luis Suarez", 7,"gmail.com"));
Store.print();
Store.clear();
Store.print();
Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));
Store.add(new Employee ("Andy Carroll", 1171,"yahoo.com"));
Store.add(new Employee ("Luis Suarez", 7,"gmail.com"));
Store.print();
Store.remove("Andy Carroll");
Store.print();
}
}
//Imports.
import java.util.HashMap;
//********************************************************************
import java.util.Map;
public class EmployeeStore
{
HashMap<String, Employee> map;
//Constructor.
public EmployeeStore()
{
map = new HashMap<String,Employee>();
}
//********************************************************************
//Hashmap Methods.
//Add to the Hashmap : Employee.
public void add(Employee obj)
{
map.put(obj.getEmployeeName(), obj);
}
//********************************************************************
//Remove from the Hashmap : Employee.
public void remove(String key)
{
//Remove the Employee by name.
map.remove(key);
}
//********************************************************************
//Clear the Hashmap : Employee.
public void clear()
{
map.clear();
}
//********************************************************************
//Print the Hashmap : Employee.
public void print()
{
System.out.println("\n********Employee's in the Company.********");
for (Employee employee : map.values())
{
System.out.println("Employee Name:\t" + employee.getEmployeeName());
System.out.println("Employee Id:\t" + employee.getEmployeeId());
System.out.println("E-mail:\t"+ employee.getEmployeeEmail());
}
}
//********************************************************************
//********************************************************************
}
//Imports:
//********************************************************************
//Employee Class.
public class Employee
{
//Variables.
private String employeeName;
private int employeeId;
private String employeeEmail;
//********************************************************************
//Constructor.
public Employee(String employeeName, int employeeId, String employeeEmail)
{
this.employeeName = employeeName;
this.employeeId = employeeId;
this.employeeEmail = employeeEmail;
}
//********************************************************************
//Getters.
public String getEmployeeEmail() {
return employeeEmail;
}
public void setEmployeeEmail(String employeeEmail) {
this.employeeEmail = employeeEmail;
}
public String getEmployeeName() {
return employeeName;
}
public int getEmployeeId() {
return employeeId;
}
//********************************************************************
//toString method.
public String toString() {
return "Employee [employeeName=" + employeeName + ", employeeId="
+ employeeId + ", employeeEmail=" + employeeEmail + "]";
}
//********************************************************************
}

Since this is homework I'll only guide you.
You have two options:
First of them is to create additional maps, mapping id-Employee and email-Employee, then fill all three maps when adding new employee. Getting employee would require to use Map.get(key) method on one of those maps.
Second, seems like better suiting your need, option is to retrieve all values from map - using Map.values(), iterate over them (using foreach), and check if id or email of given employee is the one that you was looking for - using object.equals(object2) method.
and one last thing - try to write clean code, so be precise in naming - in place of:
public void add(Employee obj)
{
map.put(obj.getEmployeeName(), obj);
}
try following:
public void add(Employee employee)
{
map.put(employee.getEmployeeName(), employee);
}
It does make the difference, trust me :)
EDIT:
Going back to naming advice - When you have class Named Employee its redundant to name method with word Employee within - as you did with employee.getEmployeeName().
It's quite obvious, that you want to get name of empoyee, not his dog, nor couch :) employee.getName() (that gets value of field named name - not myName or employeeName) is simpliest and best idea that you shoud have :)

Related

how to do a keyword search in a list of java objects matched against all the members of the java object

I have a List<Employee> which contains multiple members like id, name, designation, level, role, domain, account, etc.
I want to search a keyword against all the members of Employee in the entire list and return a list containing all matched instances Employee.
Here is a sample of my Employee class:
public class Employee
{
public String name { get; set; }
public String email { get; set; }
public String designation{ get; set; }
public String level { get; set; }
public String domain { get; set; }
public String role { get; set; }
}
More like a keyword search on any e-commerce website like Walmart or Amazon.
I don't want to write a series of if statements in a loop to match against each member. One way I think is to create another string that holds the concatenated value of each member in the Employee object and then uses Java 8 streams to do a search but I think there would be a better way.
Any more suggestions?
You can use reflection to loop through all fields and compare the values, so create this method in Employee class:
public class Employee{
/* Instance Members */
public boolean checkMatch(String keyword) throws IllegalAccessException {
for(Field field: this.getClass().getDeclaredFields()){
String value = (String) field.get(this);
if(value.equalsIgnoreCase(keyword))
return true;
}
return false;
}
}
USAGE:
public static void main(String[] args) throws IllegalAccessException {
List<Employee> employees = new ArrayList<>();
String keyword = "Research";
employees.add(new Employee("john","john#doe.com","Manager","3rd","Research","Senior"));
for(Employee e: employees){
if(e.checkMatch(keyword)){
System.out.println("Yayy! Record Found");
}
}
}

One of my classes will not output anything

so I need some advice, I have been working on some code for quite a while and I can never seem to find out why my code is screwing up terribly. It seems as if one of the toString lines in my Product class is not working properly. Here is the code:
import java.util.ArrayList;
public class lab24ArrayList
{
public static void main(String[]args)
{
ShoppingCart cart = new ShoppingCart();
Product hat = new Product ("Hat", 10);
Product scarf = new Product ("Scarf", 8);
Product legos = new Product ("Legos", 19);
Product dvd = new Product ("DVD", 12);
System.out.println("Removing DVD: "+cart.remove(dvd));
cart.add(hat);
cart.add(scarf);
cart.remove(scarf);
System.out.println("Removing Scarf: " +cart.remove(scarf));
cart.add(legos);
cart.add(dvd);
cart.add(legos);
System.out.println(cart);
}
}
class ShoppingCart
{
ArrayList <Product> cart;
public ShoppingCart()
{
cart = new ArrayList<Product>();
}
public int size()
{
int k = cart.size();
return k;
}
public void add(Product p)
{
cart.add(p);
}
public Product remove(Product p)
{
if(cart.contains(p))
{
cart.remove(p);
return p;
}
else
return null;
}
}
class Product
{
private String name;
private double price;
public Product(String _name, double _price)
{
name = _name;
price = _price;
}
public String getName() {return name;}
public double getPrice() {return price;}
public String toString() {return name + ": $"+price;}
}
When I put it in the compiler, all I get is this:
Removing DVD: null
Removing Scarf: null
ShoppingCart#c2f0bd7
When I need to get this:
Removing DVD: null
Removing Scarf: Scarf: $8
Items: 6
Total: $60.00
Hat: $10
Legos: $19
DVD: $12
Legos: $19
You're missing a toString() method on your ShoppingCart, that's why you get ShoppingCart#c2f0bd7. Override toString() in the ShoppingCartclass to build a string from the items within it.
You're also removing the Scarf twice, once here cart.remove(scarf) then also in System.out.println("Removing Scarf: " +cart.remove(scarf)).
To clarify how to print out the cart, you'll want to create a toString method in ShoppingCart similar to what you've done in Product:
public static String toString() {
StringBuilder stringBuilder = new StringBuilder();
for(Product product : cart) {
stringBuilder.append(product);
}
return stringBuilder.toString();
}
That creates a StringBuilder, loops through each product in the cart and appends it to the StringBuilder. You then return that string.

Using HashSet with a user class Employee

I know this will sound a very dumb question, but I got confused after what I have known about HashSet and what I see when I execute below code.
I have an Employee class as follows (keeping only relevant piece of code):
public class Employee {
//assume it has 3 variable name(String),salary(double) and id(int)
//assume the constructor, getter-setters are there
//following is my equals and hashCode implementation
public boolean equals(Employee e){
return name.equals(e.name);
}
public int hashCode(){
return id;
}
}
Now I have following code which uses HashSet :
Employee e1 = new Employee("Abc", 2.0, 1);
Employee e2 = new Employee("abc", 3.0, 4);
Employee e3 = new Employee("XYZ", 4.0, 3);
Employee e4 = new Employee("Mno", 5.0, 2);
Employee e5 = new Employee("Abc", 77.0, 1);
Set<Employee> sEmp = new HashSet<Employee>();
sEmp.add(e1);
sEmp.add(e2);
sEmp.add(e3);
sEmp.add(e4);
sEmp.add(e5);
for(Employee e : sEmp){
System.out.println(e);
}
So I get all the objects data being printed on my console as :
Abc 77.0 1
Abc 2.0 1
Mno 5.0 2
XYZ 4.0 3
abc 3.0 4
AFAIK, the set does not allow duplicates and this duplicay will be check on equals (correct me if I am wrong).
Also, HashSet uses the hashCode, so in above case, it should not add the object e5. But it successfully adds that element to the set. This confused me.
(Please ignore if I have missed standards and all that stuff, I am trying to understand the concept/implementation).
EDITED : This may sound a dumb question, but I am preparing for certification ans was trying to see how stuff works.
You're overloading equals rather than overriding it. Its parameter should be of type Object.
But also your hashCode is checking the id while equals is checking the name. They should probably be constructed from the same properties.
This is standard example of why we should be using #Override annotation wherever possible.
If you would use this annotation with your equals method, you would be informed by compiler that you are not overriding equals method, because there is no equals(Employe) method in superclass, but equals(Object). So you are overloading this method (you are creating additional method with different arguments).
Because of this HashSet is not using code of your equals method, but code from equals(Object) method inherited from Object class which just checks references equality:
public boolean equals(Object obj) {
return (this == obj);
}
I have added some more code in equals methods. This will allow you to update the latest value for the employee id.
package com.test.day16;
import java.util.HashSet;
import java.util.Set;
/**
*
* #author PradeepPadmarajaiah
*
*/
public class Employee {
private int empId;
private String empName;
public Employee(int empId, String empName) {
super();
this.empId = empId;
this.empName = empName;
}
/**
* #return the empId
*/
public final int getEmpId() {
return empId;
}
/**
* #param empId
* the empId to set
*/
public final void setEmpId(int empId) {
this.empId = empId;
}
/**
* #return the empName
*/
public final String getEmpName() {
return empName;
}
/**
* #param empName
* the empName to set
*/
public final void setEmpName(String empName) {
this.empName = empName;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + "]";
}
#Override
public int hashCode() {
return this.empId;
}
#Override
public boolean equals(Object obj) {
Employee employee = (Employee) obj;
if (employee.empId == this.empId) {
employee.setEmpName(this.empName);
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Set<Employee> employees = new HashSet<>();
employees.add(new Employee(1, "Raj"));
employees.add(new Employee(1, "Pradeep"));
employees.add(new Employee(1, "Kumar"));
employees.add(new Employee(2, "Chandan"));
employees.add(new Employee(2, "Amitava"));
System.out.println(employees);
}
}
Check the line "employee.setEmpName(this.empName);" This will override the value of id. This means, empId 1 will have latest empName value as Kumar
Else, empId 1 will have empName value as Raj which was first assigned and it will not ovverride the value to Kumar after checking
This work similar to the HashMap mechanism now.
Code Result will be
[Employee [empId=1, empName=Kumar], Employee [empId=2, empName=Amitava]]

ArrayList won't print in console

I have an Employee class with one method named addEmployee which manipulates an ArrayList to add employees. My following code won't print the list on the console screen. I can't find out what's wrong with my code.
package com.sib.Tmanager;
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
private String EmpFName;
private String EmpLName;
public Employee(String empFName, String empLName) {
super();
EmpFName = empFName;
EmpLName = empLName;
}
public String getEmpFName() {
return EmpFName;
}
public void setEmpFName(String empFName) {
EmpFName = empFName;
}
public String getEmpLName() {
return EmpLName;
}
public void setEmpLName(String empLName) {
EmpLName = empLName;
}
public static void addEmployee()
{
ArrayList<Employee> Emplist= new ArrayList<Employee>();
Scanner s=new Scanner(System.in) ;
System.out.println("Enter the Firstname of the employee");
String Fname= s.next();
System.out.println("Enter the Lastname of the employee");
String Lname= s.next();
Employee emp = new Employee(Fname, Lname);
Emplist.add(emp);
//System.out.println(emp.EmpFName +" "+ emp.EmpLName);
System.out.println(Emplist);
}
}
I tried to change my code by overriding the ToString() method and I still have the same following output.
Enter employee's Firstname
jason
Enter employee's Lastname
karl
[com.sib.Tmanager.Employee#1a758cb]
This may not be an answer, but a bit of advice about class design.
Think about an Employee as a physical object.
Should an Employee have a first name? Yes.
Should an Employee have a last name? Yes.
Should an Employee be filled with other Employyes? Absolutley not.
If the above third point doesn't make sense, what should you do?
Create a class called something like EmployeeList. Should an EmplpoyeeList have Employees? Why, of course!
The above class is the class you want to have the Employee ArrayList
Also, this is where you want to have the addEmployee method, so you can add the Employee the EmployeeList
Here's a example
public class EmployeeList {
ArrayList<Employee> employees;
public EmployeeList() {
employees = new ArrayList<Employee>();
}
public void addEmployee(Employee employee) {
employees.add(employee);
}
public void printEmployees() {
for (Employee e : employees) {
System.out.println(e);
}
}
}
So in the main, you first will create an EmployeeList then add Employees to it.
public static void main(String[] args) {
EmployeeList list = new EmployeeList();
list.addEmployee(new Employee("Jim", "Bo");
list.addEmployee(new Employee("Foo", "Bar");
list.addEmployee(new Employee("First", "Last");
list.printEmployees();
}
Note: to get the Employee object to print out as String representation, you should override the toString() method as others have suggested.
You can use Arrays.toString(empList.toArray(new Employee[0])) or empList.toString() in order to print the contents of an ArrayList. This will print nicely if you override toString() in Employee.
call AddEmployee() from public static void main()
System.out.println(Emplist)
you are trying to print Emplist object
you have to iterate the arraylist to show it's content
You should assign the ArrayList in the class fields and initialize it in the Constructor
public class Employee {
private String EmpFName;
private String EmpLName;
private ArrayList<Employee> Emplist;
.
.
.
}
public Employee(String empFName, String empLName) {
super();
ArrayList<Employee> Emplist= new ArrayList<Employee>();
EmpFName = empFName;
EmpLName = empLName;
}
Now when you need to add you only do :
this.Emplist.add(x);
in the addEmployee method

How can I print from this object? Java

I need to print the first name, last name, and salary from two employee objects but I keep getting a cannot find symbol error. What would I do to fix this?
Here is the constructor class:
public class Employee
{
private String firstName;
private String lastName;
private double monthlySalary;
public Employee( String firstName1, String lastName1, double monthlySalary1) {
setfirstName(firstName1);
setlastName(lastName1);
setmonthlySalary(monthlySalary1);
}
String getfirstName() {
return firstName;
}
String getlastName() {
return lastName;
}
double getmonthlySalary() {
return monthlySalary;
}
public void setfirstName (String firstName1) {
firstName = firstName1;
}
public void setlastName (String lastName1) {
lastName = lastName1;
}
public void setmonthlySalary (double monthlySalary1) {
monthlySalary = ( monthlySalary1 >= 0 ? monthlySalary1 : 0);
}
}
And here is what I have so far to print the objects:
public class EmployeeTest {
public static void main(String[] args) {
Employee a = new Employee("John", "Smith", 10000);
Employee b = new Employee("Jane", "Smith", 11000);
System.out.print(a.firstName1);
}
}
I need to be able to have it print out something along the lines of "Name: Salary:" But I am clueless as to how to make this work. Any help would be greatly appreciated.
In your employee class, you need to override the toString() method.
You can try something like:
#Override
public String toString()
{
System.out.println("Name: "+name+"Salary: "+salary);
}
Then for each of your employees, when you want to print them, just call
System.out.println(employee);
You cant print out firstName (or firstName1, because that doesnt exist in your class), because its marked as private. You should do something like this:
System.out.print(a.getfirstName())
firstName is private, which means that it cannot be seen outside of the object/class it resides in. I suggest you try overriding the toString() method on your Employee class. That method would have access to all the private members of Employee.
Alternately, you could use getfirstName() to return the first name.
Also, this may be a typo, but there is no firstName1 in Employee - it is firstName.

Categories

Resources