Reputation: 77
I'm quite new to java and I am trying to create a set out of objects that are acquired through lambda expressions in a map. Basically, I am getting a value from the map (lambda expression) and running it to get a Boolean. However, I'm getting an error when running the .apply on the expression. Any ideas on how to fix this? Any help is appreciated.
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());
}
}
Upvotes: 0
Views: 965
Reputation: 88707
Since you seem to apply the same predicate to all elements in tenant_subscriptions
you could use a stream:
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
Upvotes: 0
Reputation: 44952
Predicate
functional interface has test()
method, not apply()
:
if (order_function.get(DataProduct).test(s)){
orderable_sub.add(s.getIndexId());
}
Upvotes: 2