Commits

Bogdan Mart committed 1045a36

Sum and Product with selectors

  • Participants
  • Parent commits 76916eb

Comments (0)

Files changed (1)

File src/main/java/com/innahema/collections/query/queriables/Queryable.java

         Arithmetic<?> acc=null;
         for (T val : this)
         {
+            if(val == null)
+                continue;
             if (acc==null)
             {
                 acc = new Arithmetic<>((Number)val);
         Arithmetic<?> acc=null;
         for (T val : this)
         {
+            if(val == null)
+                continue;
             if (acc==null)
             {
                 acc = new Arithmetic<>((Number)val);
         return (acc != null ? uncheckedCast(acc.value()) : null);
     }
 
+
+    /**
+     * Calculates sum of all objects selected from collection
+     * @return sum of all objects
+     * @throws ArithmeticException in case if TRes type isn't processable by {@link Arithmetic GenericArithmetic}
+     * @param selector function to select objects to sum
+     * @param <TRes> type of objects to sum
+     */
+    @Nullable
+    public <TRes extends Number> TRes sum(Function1<T,TRes> selector) throws ArithmeticException
+    {
+        Arithmetic<TRes> acc=null;
+        for (T val : this)
+        {
+            if(val == null)
+                continue;
+            if (acc==null)
+            {
+                acc = new Arithmetic<>(selector.apply(val));
+                continue;
+            }
+            acc.add(selector.apply(val));
+        }
+        return (acc != null ? acc.value() : null);
+    }
+
+    /**
+     * Calculates production of all objects selected from collection
+     * @return production of all objects
+     * @throws ArithmeticException in case if TRes type isn't processable by {@link Arithmetic GenericArithmetic}
+     * @param selector  function to select objects to product
+     * @param <TRes> type of objects to product
+     */
+    @Nullable
+    public <TRes extends Number> TRes product(Function1<T,TRes> selector)  throws ArithmeticException
+    {
+        Arithmetic<TRes> acc=null;
+        for (T val : this)
+        {
+
+            if(val == null)
+                continue;
+            if (acc==null)
+            {
+                acc = new Arithmetic<>(selector.apply(val));
+                continue;
+            }
+            acc.mul(selector.apply(val));
+        }
+        return (acc != null ? acc.value() : null);
+    }
+
     /**
      * Just for semantic compatibility (if you want to calculate sum for non numeric type).
      * It just redirects to {@link Queryable#fold(Function2)}