Is there a safe Java implementation for “shrinking"?

I often need to run shorthand (also called foldl / foldr, depending on your contexts) in java to aggregate Itterable elements.

The abbreviation accepts the / iterable / etc collection, a two-parameter function, and an optional initial value (depending on implementation details). The function is sequentially applied to the collection element and the output of the previous reduction call until all elements are processed and the final value is returned.

Is there a safe implementation of shorthand in any common java-api? Google Collections it seems that he should have one, but I could not find him. (perhaps because I don't know what other names he will use.)

+7
java collections reduce
source share
3 answers

you could easily roll your own video based on your description:

public interface Reducer<A, T> { public A foldIn(A accum, T next); } 

Then using the strategy template:

 public class Reductor<A, T> { private Reducer<A, T> worker; public Reductor<A, T>(Reducer<A, T> worker) { this.worker = worker; } public A fold(A rval, Iterator<T> itr) { while(itr.hasNext()) { A rval = worker.foldIn(rval, itr.next()); } return rval; } } 

I'm sure there are a ton of syntax errors, but the main thing (there are several options that you could make about how to get an empty battery value. Then, to use it on a particular iterator, just define your gear to fly:

 Reductor r = new Reductor<A, T>(new Reducer<A, T>() { public A foldIn(A prev, T next) { A rval; //do stuff... return rval; } } A fold = r.fold(new A(), collection.getIterator()); 

depending on how your iterator works, it can fold left or fold right while the iterator goes in the right direction.

hope this helps.

+2
source share

Based on Luke's suggestion, here is a legitimate implementation of Java:

 public interface Reducer<A,T> { A foldIn(A accum, T next); } public static <T> T reduce(final Reducer<T,T> reducer, final Iterable<? extends T> i) { T result = null; final Iterator<? extends T> iter = i.iterator(); if (iter.hasNext()) { result = iter.next(); while (iter.hasNext()) { result = reducer.foldIn(result, iter.next()); } } return result; } public static <A,T> A reduce(final Reducer<A,T> reducer, final Iterable<? extends T> i, final A initializer) { A result = initializer; final Iterator<? extends T> iter = i.iterator(); while (iter.hasNext()) { result = reducer.foldIn(result, iter.next()); } return result; } 
+2
source share

Try the funons package . It was in the sandbox forever, but I think he will do what you want.

+1
source share

All Articles