Reputation: 551
Let's consider the following method, that allows me get the items of a generic Map filtering the item that have a geneiric attribute== to a Value (it is not a my code):
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Utilities {
public static <T> List<T> getObjectWithAttributeEqualTo(Map<?, T> MyMap_Arg, Function<T, ?> MY_AttributeValueExtractor_Arg, Object MY_AttributeValueToEqual_Arg) {
return MyMap_Arg.values().stream()
.filter(o -> MY_AttributeValueExtractor_Arg.apply(o).equals(MY_AttributeValueToEqual_Arg))
.collect(Collectors.toList());
}
}
PROBLEM: how to invoke and use this method?
let's say I have a Class called 'Car' with a NOT STATIC method 'getColor()'. I have the object 'myHashMap', that is a map of car, then declared as
HashMap<Integer, Car> myHashMap ;
I want for example get the list of red cars inside my myHashMap.
Upvotes: 0
Views: 124
Reputation: 551
FOUND SOLUTION:
List<Car> redCars = Utilities.getObjectWithAttributeEqualTo(myHashMap, object->object.getColor(), "red");
Upvotes: 0
Reputation: 81
This code works fine in Eclipse Oxygen, I think your IDE is wrong giving you a 'not static' error:
List<Car> redCars = getValuesWithAttributeEqualTo(myHashMap, Car::getColor, "red");
Upvotes: 1