如何在地图上运行作为值的Lambda表达式

时间:2019-04-15 13:15:11

标签: java lambda maps

我对Java还是很陌生,我正在尝试创建一组通过映射中的lambda表达式获取的对象。基本上,我从映射(lambda表达式)中获取一个值,并运行它以获取布尔值。但是,在表达式上运行.apply时出现错误。有想法该怎么解决这个吗?任何帮助表示赞赏。

        Map<String, Predicate<IndexSub>> order_function = new HashMap<>();
        order_function.put("AlternativesValues", x -> false);
        order_function.put("AlternativesConstituent", x -> x.getCloseCons());
        order_function.put("EquityValues", x -> false);
        order_function.put("EquityCloseConstituent", x -> x.getCloseCons());
        order_function.put("EquityOpenConstituent", x -> x.getOpenCons());
        order_function.put("FixedValues", x -> false);
        order_function.put("FixedReturns", x -> x.getCloseCons());
        order_function.put("FixedStatistics", x -> x.getOpenCons());

        //getCloseCons and getOpenCons return true/false    

        Set<String> orderable_sub = new HashSet<String>();

        for (IndexSub s : tenant_subscriptions) {
                                 //DataProduct is a string
            if (order_function.get(DataProduct).apply(s) == true){
                orderable_sub.add(s.getIndexId());
            }

        }

2 个答案:

答案 0 :(得分:2)

Predicate功能界面具有test()方法,而不是module.exports.verifyStandardMetadata = data => { .... }

apply()

答案 1 :(得分:0)

由于您似乎将相同的谓词应用于tenant_subscriptions中的所有元素,因此可以使用流:

Predicate<IndexSub> p = order_function.get(dataProduct);

if( p == null ) {
  //handle that case, e.g. set a default predicate or skip the following part
}

//this assumes tenant_subscriptions is a collection, if it is an array use Arrays.stream(...) or Stream.of(...)
Set<String> orderable_sub = tenant_subscriptions.stream() //create the stream
                               .filter(p) //apply the predicate
                               .map(IndexSub::getIndexId) //map all matching elements to their id
                               .collect(Collectors.toSet()); //collect the ids into a set