I started with C# and now I'll work with to Java. I need to implement a simple linq query(filter + get) in Java.
The C# equivalent could be:
public interface IPriceRule
{
bool IsMatch(OrderItem item);
decimal CalculatePrice(OrderItem item);
}
//
_pricingRules = new List<IPriceRule>();
//...
public decimal CalculatePrice(OrderItem item)
{
return _pricingRules.First(r => r.IsMatch(item)).CalculatePrice(item);
}
Knowing that java doesn't have Linq, the first thing that come to me are extension methods, but also did not exist. Then I have to do all (Maybe I get bad habits for cause of the simplicity):
@Override
public BigDecimal CalculatePrice(OrderItem item) {
IPriceRule _selectedRule = getFirstItemThatMatch(_pricingRules, item);
if(_selectedRule != null)
return _selectedRule.CalculatePrice(item);
else
return BigDecimal.ZERO;
}
private IPriceRule getFirstItemThatMatch(List<IPriceRule> prmCollection, OrderItem item) {
IPriceRule _result = null;
for(IPriceRule itemPriceRule : prmCollection) {
if(itemPriceRule.IsMatch(item)) {
_result = itemPriceRule;
break;
}
}
return _result;
}
I am not convinced that this java code are equivalent, optimal. Maybe exist a technique to optimize and improve it in terms of algorithmic complexity and coding speed.
I believe that .net optimize and normalize the queries and bring it to you with linq, compared with the code that you could write.