Reputation: 3018
I have a list of Entity, all entities have unique name, currently to get unique value, I am using MAP of entity name and Entity Object. I dont want to use map just for filter purpose.
I found one solution, but it usage Java-8.
There is one API in Google Guava com.google.common.collect.Sets.filter(), but it returns Set and in this case I have to get 0th element.
Can anyone suggest better approach.
Upvotes: 0
Views: 375
Reputation: 4113
Using the Map approach gives you time benefit as lookup time is reduced whereas, but uses memory.
If you are open to Guava try something like:
Optional<Entity> result = FluentIterable.from(entityList).firstMatch(new Predicate<Entity>() {
@Override
public boolean apply(Entity entity) {
return entity.getName().equals(input); //Input can be from variable in function definition
});
);
Something like this, can solve.
Upvotes: 2
Reputation: 596
Try below method:
public static Entity findByName(String name, List<Entity> entities) {
if (entities!= null && name != null) {
for (Entity e : entities) {
if (name.equals(e.getName())) {
return e;
}
}
}
return null;
}
Upvotes: 0