user3763857
user3763857

Reputation: 1

Search in an arraylist by keywords

How can I search an arraylist on Java by a keyword in a way that it returns me all of the objects attributes?

For example, I have a List called Employee, that has a code, name and salary. I would like to get its salary and code searching by his Name. How can I do that? Thank you

Upvotes: 0

Views: 1830

Answers (3)

Kyranstar
Kyranstar

Reputation: 1720

This is a method that returns the first employee with the name in the list employees.

//gets an Employee from the list
public Employee getEmployeeByNameAndRemove(String name){ 
    ArrayList<Employee> employees; //this is where you'd get your list of employees

    for(int i = 0; i < employees.size(); i++){
        Employee dude = employees.get(i);
        if(dude.getName().equals(name)){
            employees.remove(i);
            return dude;
        }
    }
}

This is how you call the method.

Employee dude = getEmployeeByNameAndRemove("Johnson");
int ID = dude.getID();
int salary = dude.getSalary();

assuming that you have the methods getID() and getSalary() in your class Employee.

Upvotes: 0

bigbeno37
bigbeno37

Reputation: 5

Would it be possible to create an Employee class that contains an ArrayList of code, name and salary with getters / setters? That way, in your ArrayList, you can just store Employee objects, and in a for loop, you can use, for instance if(currentEmployeeObject.getSalary == 55000){} in a for loop that iterates over every item in that ArrayList.

Upvotes: 0

Here's how you do it.

  1. Use a for loop to iterate over your ArrayList of Employees.
  2. inside that for loop, check to see if the current Employee's name is equal to the name you're searching for.
  3. If the names are equal, then return that Employee

Upvotes: 1

Related Questions