Как запустить лямбда-выражение, которое является значением на карте - PullRequest
0 голосов
/ 15 апреля 2019

Я довольно новичок в Java и пытаюсь создать набор объектов, которые получены с помощью лямбда-выражений на карте.По сути, я получаю значение из карты (лямбда-выражение) и запускаю его, чтобы получить логическое значение.Тем не менее я получаю сообщение об ошибке при запуске .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 ]

2 голосов
/ 15 апреля 2019

Predicate функциональный интерфейс имеет метод test(), а не apply():

if (order_function.get(DataProduct).test(s)){
    orderable_sub.add(s.getIndexId());
}
0 голосов
/ 15 апреля 2019

Поскольку вы, кажется, применяете один и тот же предикат ко всем элементам в 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...