简体   繁体   中英

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):

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.

这段代码在Eclipse Oxygen中运行良好,我认为您的IDE错误,给您一个“非静态”错误:

 List<Car> redCars = getValuesWithAttributeEqualTo(myHashMap, Car::getColor, "red");

找到的解决方案:

List<Car> redCars = Utilities.getObjectWithAttributeEqualTo(myHashMap, object->object.getColor(), "red");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM