Detect duplicate email id in arraylist containg multiple employee objects - java

Suppose I have a arraylist , I am dynamically adding multiple employee objects to the arraylist. Employee object have field like Id, name, email . My requirement is when I am adding a employee object to arraylist. Suppose that object having a email which is already there of another object added to arraylist. Then it should not allow to add current object to the arraylist or show some error message.Is there any methods available in Collection module to achieve this thing in shortest possible way..

if i got your question correctly u need to avoid duplicates for employee object based on emailaddress attribute. I would recommend to use Sets instead of arraylist.
this is how you would do with sets with overriding equals and hashcode.
package com.test.testing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
Employee employee = new Employee("anilhk#gmail.com", "1");
Employee employee2 = new Employee("abc#gmail.com", "2");
Employee employee3 = new Employee("anilhk#gmail.com", "3");
List<Employee> empList = new ArrayList<Employee>();
empList.add(employee);
empList.add(employee2);
empList.add(employee3);
System.out.println("Employee List " +empList);
Set<Employee> empSet = new HashSet<Employee>();
for (Employee emp : empList) {
if (empSet.contains(emp)) {
System.out.println("Employee with employee email " +emp.getEmailAddress() + " and employee id " +emp.getId() +" already exists");
}
else {
empSet.add(emp);
}
}
System.out.println(empSet);
}
private static class Employee {
private String emailAddress;
private String id;
#Override
public String toString() {
return "Employee [emailAddress=" + emailAddress + ", id=" + id + "]";
}
public Employee(String emailAddress, String id) {
this.emailAddress = emailAddress;
this.id = id;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((emailAddress == null) ? 0 : emailAddress.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Employee)) {
return false;
}
Employee other = (Employee) obj;
if (emailAddress == null) {
if (other.emailAddress != null) {
return false;
}
} else if (!emailAddress.equals(other.emailAddress)) {
return false;
}
return true;
}
}
}
output.
Hello World!
Employee List [Employee [emailAddress=anilhk#gmail.com, id=1], Employee [emailAddress=abc#gmail.com, id=2], Employee [emailAddress=anilhk#gmail.com, id=3]]
Employee with employee email anilhk#gmail.com and employee id 3 already exists
[Employee [emailAddress=anilhk#gmail.com, id=1], Employee [emailAddress=abc#gmail.com, id=2]]
employee3 is having the same email address as employee and thus that is excluded from the list.
HTH

// Use LinkedHashMap to keep insertion order
Map<String, Employee> employees = new LinkedHashMap<>();
// v1: add new employee with unique email
employees.putIfAbsent(employee.getEmail(), employee);
// v2: add new employee and show message for duplication email
if(employees.containsKey(employee.getEmail()))
System.out.println("Email " + employee.getEmail() + " duplication");
else
employees.put(employee.getEmail(), employee);
// get all employees in order they were added
List<Employee> res = new ArrayList<>(employees.values());

You have to write a function which will go through all the nodes of array list and check it your current email address is present before or not . if it present then return false or true and display message.

More efficient way would be to keep a separate set of emails(Set< String > emailSet), and check it every time before adding an employee to the list:
if (!emailSet.contains(emp.getEmail()) {
employeeList.add(emp);
emailSet.add(emp.getEmail());
} else {
//show error message
}

Related

Which collection for sorted unique dataset?

I want to have a Collection with the following requirements:
1.) before inserting an element it checks if there is already a element with the same name, if there is, the element is not inserted
2.) after inserting, the collection is automatically sorted by the salary of the persons in the collection
I insert persons with name and salary as attributes.
Which collection does fit these requirements?
What about a TreeSet ?
You may need to use the constructor with a Comparator.
You can use TreeSet and implement Comparator to sort the needed proprty. See
this sample.
To discard the duplicate entry, you need to return 0 value;
public int compare(Empl e1, Empl e2) {
if(e1.getName().equals(e2.getName())) {
return 0;
}else if(e1.getSalary() > e2.getSalary()){
return 1;
}else if(e1.getSalary() == e2.getSalary() && (e1.getName().compareTo(e2.getName()) > 1)) {
return 1; // if the salary is equal, sort it based on name.
}
else {
return -1;
}
}
Louis is wrong!
A SortedSet would be the perfect.
You only have to implement the Comparable interface and compare the salary of the people.
it will be fine for the SortedSet, but don't forget to implements the interface COMPARABLE.
You can use a TreeSet over a HashSet, but Person has to implement Comparable interface (int compareTo(Person o) method) and override equals and hashCode methods to check the identity/unique based only on name field.
First create Person and implement/overrride methods :
public class Person implements Comparable<Person> {
public Person(String name, double salary) {
this.name = name;
this.salary = salary;
}
public Person() {
}
private String name;
private Double salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Person{" + "name=" + name + ", salary=" + salary + '}';
}
public int compareTo(Person o) {
return salary.compareTo(o.getSalary());
}
#Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
return true;
}
}
then create a HashSet and fill it with Person elements. The set will contain only elements with unique name attribute, that's done by using only name field in equals and hashCode methods.
To keep collection sorted - create a TreeSet using parameterized constructor - new TreeSet(Collection coll) , you have collection already populated with unique elements, so the sorting will take place during TreeSet initialization.
Here is the rest of snippet
public class TestPerson {
public static void main(String [] args){
Person p1 = new Person("first", 1000);
Person p2 = new Person("second", 2000);
Person p3 = new Person("third", 3000);
Person p4 = new Person("first", 4000);
Person p5 = new Person("second", 5000);
TreeSet<Person> personSet = new TreeSet<Person>();
personSet.add(p1);
personSet.add(p2);
personSet.add(p3);
personSet.add(p4);
personSet.add(p5);
for (Person person : personSet){
System.out.println(" === person element sorted : "+person);
}
HashSet<Person> personHashSet = new HashSet<Person>();
personHashSet.add(p1);
personHashSet.add(p2);
personHashSet.add(p3);
personHashSet.add(p4);
personHashSet.add(p5);
TreeSet<Person> treePersonSet = new TreeSet<Person>(personHashSet);
for (Person person : treePersonSet){
System.out.println(" === person element: "+person);
}
}
}

Circular Queue in Java

I am implemeting a circular queue in java which will accept objects (Employee) as entries. Now I have a method to edit the surname of the specific object, but somehow I cannot access the surname setter method found in the Employee class from the CQueue class even though I am importing all the required packages. Here is the code:
//PACKAGES IMPORTED
package linearstructures;
import dataobjects.*;
import linearnodes.*;
public class CQueue{
Node front, rear, temp;
boolean full = false;
String key;
public AnyClass searchKey(String key)
{
temp = rear.next; // first node
do
{
if (temp.obj.getKey().equals(key))
return temp.obj;
temp = temp.next;
} while (temp != rear.next);
return null;
}
public AnyClass editObject(String key){
int choice, newSeqNo;
double newPay;
boolean exit = false;
Employee etemp = new Employee(); //INCLUDED THIS AFTER EDIT
searchKey(key);
if(searchKey(key) != null){
temp.obj.getData();
System.out.println();
System.out.println("------------------------");
System.out.print("Enter new Salary: ");
newPay = sc.nextDouble();
System.out.println("------------------------");
System.out.println();
etemp.setPay(newPay); //INCLUDED THIS AFTER EDIT
else
System.out.println("NO OBJECT WAS FOUND!");
return null;
}
}
Employee class:
package dataobjects;
public class Employee extends AnyClass
{
public String surname;
public double pay;
public Employee(){}
public Employee(int seqNo, String surname, double pay)
{
super(seqNo);
this.surname = surname;
this.pay = pay;
}
public double getSalary()
{
return pay;
}
public void setPay(double newPay)
{
pay = newPay;
}
public String getData()
{
return super.getData() + ", Surname: " + surname + ", Pay: " + pay;
}
public String getKey()
{
return surname;
}
}
AnyClass class:
package dataobjects;
public class AnyClass
{
public int seqNo;
public AnyClass(){}
public AnyClass(int seqNo)
{
this.seqNo = seqNo;
}
public int getseqNo()
{
return seqNo;
}
public void setseqNo(int seqNo) {
this.seqNo = seqNo;
}
public String getData()
{
return "Sequential Number - " + seqNo;
}
public String getKey()
{
return Integer.toString(seqNo);
}
public void edit(){}
}
Node Class
package linearnodes;
import dataobjects.*;
public class Node{
public AnyClass obj;
public Node next;
public Node(AnyClass obj){
next = null;
this.obj = obj;
}
}
Your editobject method could be something like this:
public AnyClass editObject(String key){
// ...
// Store your search result to avoid performing searchKey twice
AnyClass searchResult = searchKey(key);
if( searchResult != null ){
// Check if searchResult is an Employee object
if( searchResult instanceof Employee )
// Cast AnyClass to Employee
Employee empl = (Employee) searchResult;
// Your logic here...
// Set properties of the Employee object
empl.setPay(newPay);
// ...
return empl;
}
// Add 'else if' here, if you need to manage other Object types
// otherwise you can join previous if conditions
}
else
System.out.println("NO OBJECT WAS FOUND!");
return null;
}
Your code creates a new local Employee instance that dies when the method ends, its value will be lost because no object points to it.
for include pay "etemp.setPay(newPay);" you will change return object to Employee.
public Employee editObject(String key){
Employee etemp = new Employee(); //INCLUDED THIS AFTER EDIT
....
....
etemp.setPay(newPay); //INCLUDED THIS AFTER EDIT
return etemp;
}
because AnyClass hasn't "public double pay;"

Creating or Instiatiating an ArrayList of Objects for Each User

Alright so, I am building an online registration system for a university. It's a fairly basic system written in java so there's no database issue to worry about. My problem is this: I have a class of objects called Course. Each course has a list of attribute (id, time, instructor, etc.). Each user then, has an arraylist (or schedule if you will) of Course objects which they can add or remove. My question is how do I create an arraylist for each student/user? Would it be beneficial to have a separate arraylist of Courses like a catalog from which to choose from? Any advice on the subject would be of help. If you'd like to see an example of my code thus far let me know and I'll edit my post to include it.
public class Course {
private int courseId;
private String courseDes;
private String courseIns;
private int time;
public Course(int courseId, String courseDes, String courseIns, int time) {
courseId = this.courseId;
courseDes = this.courseDes;
courseIns = this.courseIns;
time = this.time;
}
No need to use maps; you've expressed the right relationship yourself: "Each user has an ArrayList". The way to express a has-a relationship is with instance fields:
public class Student {
private final List<Course> courses = new ArrayList<>();
//write methods that operate on courses, or make courses public
....
Representing courses as a Course object is simplest if you care about the properties of the courses in any way. If however you only need the know the course ID, or if you need to be storing a large amount of Students, you can save space by storing courses as integers or shorts and looking them up in a static table.
I would have three separate classes Courses, Student and Enrollment.
public class Course {
private int courseId;
private String courseDes;
private String courseIns;
private int time;
public Course(int courseId, String courseDes, String courseIns, int time) {
courseId = this.courseId;
courseDes = this.courseDes;
courseIns = this.courseIns;
time = this.time;
}
}
Student
public class Student {
private final int studentID;
private final String name;
private Set<Course> studentCourses;
public Student(int studentId, String name) {
this.name = name;
this.studentID = studentId;
}
public String getName(){
return this.name;
}
public int getStudentId(){
return this.studentID;
}
void addCourse(Course course) {
if(!studentCourses.contains(course)){
studentCourses.add(course);
}
else{
studentCourses.remove(course);
studentCourses.add(course);
}
}
#Override
public int hashCode() {
int hash = 7;
hash = 23 * hash + this.studentID;
hash = 23 * hash + (this.name != null ? this.name.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Student other = (Student) obj;
if (this.studentID != other.studentID) {
return false;
}
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
return true;
}
}
Enrollment
class Enrollment{
//This Map will group student with the same name
private Map<String, List<Student>> enrollment;
public Enrollment(Student student){
if(enrollment.containsKey(student.getName())){
enrollment.get(student.getName()).add(student);
}else
{
List<Student> newStudent = new ArrayList<Student>();
newStudent.add(student);
enrollment.put(student.getName(), newStudent);
}
}
public void addCourse(Student student, Course course){
try{
List<Student> studentSameName = enrollment.get(student.name);
for(Student studentEntry : studentSameName){
if(studentEntry.getStudentId() == student.getStudentId()){
studentEntry.addCourse(course);
}
}
}catch(NullPointerException e){
//student does not exist
//TODO Add Logic
}
}
public void removeStudent(Student student){
//TODO Add Logic
}
}

I want to get individual element of an arrayList in Java

I am newbie in java and I have a method that accepts 3 parameters, query the db and returns result in an arraylist form (like this [1, Java, 3, Bangalore, 10] ). How can i extract individual element so that I can assign each to a var like int id=1;String name=Java.
Below is the method that
ArrayList searchResult =jSearch.doJobSearch(techName, exp, city);
Iterator searchResultIterator = searchResult.iterator();
PrintWriter out = response.getWriter();
String arrayList[] = new String[searchResult.size()];
if(searchResultIterator.hasNext()){
for(int i =0; i<searchResult.size(); i++){
//searchResult.get(i)
out.println(searchResult.get(i));
}
}else{
out.println("No Job found in selected city");
}
ArrayList works in the sense of [index, element].
By using the get method, you're using index as the parameter and it returns the element at that position. So if you're accessing the element by it's index you already have both the id and element, but a different collection interface might suit you better like a map.
http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
Create POJO (Plain Old Java Object). I am providing example how to array list is used when store Real time Object.
package com.appkart.examples;
public class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And Add Employee into Array list and get values
package com.appkart.examples;
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<Employee>();
Employee arun = new Employee(10, "Arun");
Employee ankit = new Employee(20, "Ankit");
Employee jon = new Employee(30, "Jon");
Employee anil = new Employee(40, "Anil");
employees.add(arun);
employees.add(ankit);
employees.add(jon);
employees.add(anil);
for (Employee employee : employees) {
int id = employee.getId();
String name = employee.getName();
System.out.println("id : "+id +" name : "+name);
}
}
}

Edit method for Employee Store.(Using Hashmap)

Hey can anyone help me understand how to do an edit method for my company application. I had previously asked for help with a search method. And i think the edit method might involve the search method.
Here is my code:
EmployeeStore.
//Imports.
import java.util.HashMap;
//********************************************************************
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 employee)
{
map.put(employee.getEmployeeName(), employee);
}
//********************************************************************
//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); to print the toString of Employee class
//or:
System.out.println("Employee Name:\t" + employee.getEmployeeName());
System.out.println("Employee Id:\t" + employee.getEmployeeId());
System.out.println("E-mail:\t"+ employee.getEmployeeEmail());
}
}
public Employee get(String name){
return map.get(name);
}
/*public void searchByName ()
{
//(for(Employee e : map.values()) {...})
//and check for each employee if his/her email matches the searched value
for(Employee e : map.values())
{
System.out.println(e);
map.equals(getClass());
}
}*/
//********************************************************************
public Employee searchByName(String name)
{
Employee employee = map.get(name);
System.out.println(employee);
return employee;
}
//********************************************************************
public Employee searchByEmail(String email)
{
for (Employee employee : map.values())
{
if (email.equals(employee.getEmployeeEmail()))
{
System.out.println(employee);
return employee;
}
}
return null;
}
//********************************************************************
//********************************************************************
//********************************************************************
}
Employee class.
//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 "\t\t\tEmployee\n" +
"********************************************************************\n"+
"Employee Name: "+ employeeName +"\n"+
"Employee Id: " + employeeId +"\n"+
"Employee Email: " + employeeEmail;
}
//********************************************************************
}
You can use the put method of java's HashMap for this as well. From the API for HashMap's put method:
If the map previously contained a mapping for this key, the old value is replaced.
So, something like:
public void edit(Employee employee)
{
map.put(employee.getEmployeeName(), employee);
}
And then in the other code:
Employee employee = getEmployeeByName("Someniceemployeename");
if (employee != null)
{
employee.setEmployeeEmail("awesomeness#stackoverflow.com");
edit(employee);
}
As for editing the ID of an employee, you need to take some additional precautions. First, you want to make sure that the map contains the ID you want to edit (as usual). Second, when "editing" the ID you need to first remove the old employee instance from the map (with the old ID) and then add the new employee with put.

Categories

Resources