1

I have a List of Employee object.

class Employee{  
  private int empId;  
  private String name;  
}  

Now I have

List<Employee> empList = new ArrayList<Employee>();  

How can I find, if my list contains an employee named "ABC"??
empList.contains("ABC"); wont work...

Should I put it in Map?? Which one is more efficient??

Just wanted to mention that I get my Employee object from database....

deejay
  • 575
  • 1
  • 8
  • 24
  • How could an `Employee` ever equal a `String`? – David Conrad Sep 19 '14 at 18:23
  • You are not declaring type for `empId` and `name`. May be you want `private int empId;` and `private String name;` – afzalex Sep 19 '14 at 18:28
  • @afzalex - thanks... a typo.. .actually I have made a scenario to just simulate my problem – deejay Sep 19 '14 at 18:43
  • Just wanted to let you all know, that I get my Employee object from the database, in that case, I wont be able to create new Employee object from `new` keyword. – deejay Sep 19 '14 at 19:01

5 Answers5

1

You can use

Map<String, Employee> map = new HashMap<>();
map.put("ABC", new Employee("ABC"));
map.put("John", new Employee("John"));

and then check

map.containsKey("ABC")


Should I put it in Map?? Which one is more efficient??

Because contains() method of list, calls indexOf, which needs to iterate over all elements like this

public int indexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

Where as map no need to iterate over all elements

CSchulz
  • 10,882
  • 11
  • 60
  • 114
sol4me
  • 15,233
  • 5
  • 34
  • 34
  • Don't over ride equals to check contains ... rather add a new method to check if it contains. override equals when it needs to do equality check in a different way. What wait where did you get map from ? – StackFlowed Sep 19 '14 at 18:19
  • Should I put it in Map?? Which one is more efficient?? posted by OP – sol4me Sep 19 '14 at 18:27
1

Override equals. You can then use List.contains

class Employee {  
    private empId;  
    private name;
    public boolean equals(Object o) {
        return (o instanceof Employee && ((Employee)o).empId == empId && ((Employee)o).name = name);
    }
}  


List l = ...;
Employee e = new Employee(...);
l.add(e);
l.contains(e);
brso05
  • 13,142
  • 2
  • 21
  • 40
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • ControlAltDel, `l.contains(e)` will return true even if you not have overriden that `equals(...)` method. – afzalex Sep 19 '14 at 19:13
  • 2
    Only if the Employee object is the same object. Using equals lets you match on the actual values – ControlAltDel Sep 19 '14 at 19:15
  • I was considering your example. – afzalex Sep 19 '14 at 19:17
  • How this answer is right. Look at the question, OP has editted it. @brso05. `contains(e)` will not return true if User create new object of `Employee` with same id and name. –  Sep 19 '14 at 19:45
1

Since you are storing the Employee objects and not String in your list , i think it is impossible to search without looping through all list objects

for (Employee employee : empList) {
      if (employee.getName().equals(searchString))
        System.out.println("Found");
    }

Note: Your Employee class should give access to name field either through getter method or change it to public


There are other alternatives, but it depends on your requirements and tradeoff's between speed, space, readability, resources etc

One thing i can think of is HashMap, which has constant time lookup in average case

HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1, "Tom");
System.out.println(hm.containsValue("Tom"));

Now,

Should I put it in Map?? Which one is more efficient??

Instead of coding and analyzing, Know Thy Complexities beforehand !

Community
  • 1
  • 1
Ravi Yenugu
  • 3,895
  • 5
  • 40
  • 58
  • I had tried the same way using iterator... but I was thinking, if there is better way to do it. FYI - I have getter setter... – deejay Sep 19 '14 at 19:40
1

In Java 8, if you wanted to determine whether the employee list contains an employee named "ABC", you could do this:

boolean containsABC = empList.stream().anyMatch(emp -> emp.getName().equals("ABC"));
Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
0

Here is the code that you can use. I am considering that you want list to return true when empId and name of the Employee matches.
I also prefer to use Constructor in your code(Just recommendation).
The below code will run as you are wanting it to be.

class Employee {

    private int empId;
    private String name;

    // below overriden function will return true if it found Employee with 
    // same ID and name
    @Override
    public boolean equals(Object obj) {
        return (obj instanceof Employee             //Checking instace of obj
            && ((Employee)obj).empId == empId       //Checking empId
            && ((Employee)obj).name.equals(name));  //Checking name
    }

    // Used constructor to create Employee
    Employee(int id, String nm) {
        empId = id;
        name = nm;
    }

}


Here is an example run :

List l = new ArrayList();
l.add(new Employee(1, "ME");
System.out.println(l.contains(new Employee(1, "ME")));  //print true

I would also like to acknowledge you that you should also override hashCode() when you decides to override equals(...) method according to Design Pattern.

afzalex
  • 8,598
  • 2
  • 34
  • 61