ASHISH
ASHISH

Reputation: 67

Searching an element in a list

How can I search in a List? Is there any in build function?

public void searchEmployee(int empId) {
    Iterator<Employee> iterator = list1.iterator();
    while (iterator.hasNext()) {
        if (iterator.next().getEmpid() == empId) {
            System.out.println("the searched employee is ::");
            iterator.remove();
        }
    }

}

Upvotes: 1

Views: 104

Answers (6)

lummycoder
lummycoder

Reputation: 608

List has .contains(Object o) and .remove(Object o)
So the better way would be

public void removeEmployee(Employee e) {
   if (listEmplyees.contains(e)) {
       listEmplyees.remove(e);
   }
}


for Emplyee object or for Id:

public void removeEmployee(int i) {
   for(Employee e: listEmplyees) {
       if(e.getId == i) {
           listEmplyees.remove(e);
       }
   }
}

Or you could store Employees in Map by their id and there would be easier to delete by id. And if you want to ensure, that employees would never be repeated - use Set and override hashCode and equals in your Employee class, so you could place break in your search loop, when you find the same object.

Upvotes: 1

fascynacja
fascynacja

Reputation: 2826

You can try use built in function binarySearch: http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#binarySearch(java.util.List, T, java.util.Comparator)

Upvotes: 0

Rahul
Rahul

Reputation: 45060

List#contains() method can be used. But in your case, since you need to search it based on empId, you need to override the equals() in your Employee class like this.

@Override
public boolean equals(Object obj) {
    if (obj != null) {
        Test other = (Test) obj;
        return i == other.i;
    } else {
        return false;
    }
}

And then you can do something like this:

list1.remove(yourEmp);

Upvotes: 1

Vimal Bera
Vimal Bera

Reputation: 10497

List has .contains() method through which you can check whether list contains that object or not. For ex : I have a list products which stores the object of product in list.

List<Product> products;
if(products.contains(tempProduct)){
     //    do some operations
}

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

In your case, As simple as you get is

for (Employee e : list) { 
    if (e.getEmpid() == empId) {
       //found here .break
    }
}

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533510

Not yet. There will be better support in Java 8, but for now you can make the code simpler

for(Employee e: list1)
    if(e.getEmptId() == empId)
        System.out.println("The searched item is " + e);

Upvotes: 1

Related Questions