Reputation: 1
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
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
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
Reputation: 31206
Here's how you do it.
for
loop to iterate over your ArrayList
of Employee
s.for
loop, check to see if the current Employee
's name is equal to the name you're searching for.Employee
Upvotes: 1