[英]How to use a method for filtering generic HashMap - Java
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): 让我们考虑以下方法,它允许我获取通用Map的项目,该项目将具有Generic属性==的项目过滤为Value(这不是我的代码):
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()'. 假设我有一个名为“ Car”的类,具有一个非静态方法“ getColor()”。 I have the object 'myHashMap', that is a map of car, then declared as 我有一个对象“ myHashMap”,它是汽车的地图,然后声明为
HashMap<Integer, Car> myHashMap ;
I want for example get the list of red cars inside my myHashMap. 例如,我想获取myHashMap中的红色汽车列表。
这段代码在Eclipse Oxygen中运行良好,我认为您的IDE错误,给您一个“非静态”错误:
List<Car> redCars = getValuesWithAttributeEqualTo(myHashMap, Car::getColor, "red");
找到的解决方案:
List<Car> redCars = Utilities.getObjectWithAttributeEqualTo(myHashMap, object->object.getColor(), "red");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.