Reputation: 323
Suppose I have a class Employee :
class Employee {
Employee(String name, int age)
{
this.name = name ;
this.age = age;
}
String name ;
int age;
}
Now Create a List of this like :
ArrayList<Employee> aa = new ArrayList<Employee>();
aa.add(new Employee("Nitish", 26));
aa.add(new Employee("Sh", 2));
aa.add(new Employee("S", 1));
Can i get Employee Object Where name value is "Nitish"? Without For loop
Upvotes: 2
Views: 9266
Reputation: 3894
I guess your interviewer just doesn't want you to use for
or while
loops to find objects in an ArrayList
, but you can actually find them "without loops".
First, you need to override equals
and hashCode
of Employee
class:
@Override public boolean equals(Object obj) {
// ...
}
@Override public int hashCode() {
// ...
}
Now you can find your object with ArrayList.indexOf (uses equals
to find match) by creating a dummy reference:
Employee target = new Employee("Nitish", 26);
int index = employees.indexOf(target);
It's kinda silly but I guess some interviewers want us to think outside-of-the-box. Even though under the hood it's using loops, but if my interviewer asks me the same question, instead of saying no you can't, I'd use this example because I want to try my best just not to use "loops" as asked, and explains how it works behind the scene. Then afterwards I'd briefly come up with other better solutions, and hope that works!
Upvotes: 1
Reputation: 87
ArrayList work on index based structure.to ADD,READ,GET value from array need to index of the specific index. instead store data on ArrayList you can use Map. Using key can be access value from Map.
Map<String, Employee> employeeMap = new HashMap<>();
employeeMap.put("Nitish", new Employee("Nitish", 26));
employeeMap.put("Sh", new Employee("Sh", 2));
employeeMap.put("S", new Employee("S", 1));
System.out.println(employeeMap.get("Nitish").getName());
System.out.println(employeeMap.get("Nitish").getAge());
Upvotes: 0
Reputation: 136012
Try this
Employee emp = aa.stream().filter(e->e.name.equals("Nitish")).findAny().orElse(null);
this version returns null if not found
Upvotes: 1
Reputation: 164089
You can use a filtered stream:
Object[] array = aa
.stream()
.parallel()
.filter((emp) -> emp.name.equals("Nitish"))
.toArray();
if (array.length > 0) {
Employee employee = (Employee)array[0];
String name = employee.name;
int age = employee.age;
System.out.println("Found Employee with Name = " + name + " and Age = " + age);
} else {
System.out.println("Not Found");
}
Upvotes: 0