Reputation: 453
What I need : Getting an Element I have created two objects from a class which has 2 attributes: id and name. After I create an object, I set it's ID and add the object to an ArrayList:
Variable variable1 = new Variable();
variable1.setID(1);
Variable variable2 = new Variable();
variable1.setID(2);
ArrayList<Variable> varList = new ArrayList<Variable>();
varList.add(variable1);
varList.add(variable2);
Then in my code I want to get the Element which has Id == 1 but I didn't find a method that can return me the Object by giving it the Object attribute.
Is there a method like this : Object o = getObjectByAttribute(Object.id==1) ?
Upvotes: 1
Views: 83
Reputation: 5109
If you are using java8, filters(in lambda expression) is a good option.
Stream<Variable> outputList = varList.stream().filter(val -> val.getId() ==1);
outputList will contain only Variable objects with Id 1. First element can be taken from that list if it is not empty.
Ref: http://zeroturnaround.com/rebellabs/java-8-explained-applying-lambdas-to-java-collections/
Upvotes: 1
Reputation: 16067
Is there a method like this : Object o = getObjectByAttribute(Object.id==1) ?
No, but it's easy to create one. Create an interface Function
that from an Object of type T give a property of type U.
interface Function<T, U> {
U apply(T t);
}
Then the method:
public static <T, U> T getObjectByAttribute(List<T> objects, Function<T, U> fromAttribute, U attributeResearched) {
for(T obj : objects) {
if(fromAttribute.apply(obj).equals(attributeResearched)) {
return obj;
}
}
return null;
}
and how to call it:
Variable v = getObjectByAttribute(varList, new Function<Variable, Integer>() {
@Override
public Integer apply(Variable variable) {
return variable.id;
}
}, 1);
Upvotes: 1
Reputation: 5318
You could make use of Collections.binarySearch()
and a custom Comparator
EDIT: code snippet:
Comparator<Variable> comparator = new Comparator<Variable>() {
public int compare(Variable o1, Variable o2) {
return Integer.compare(o1.getID(), o2.getID());
}
};
Collections.sort(varList, comparator);
Variable key = new Variable();
key.setID(1);
int index = Collections.binarySearch(varList, key, comparator);
Upvotes: 1