Mango: Transform iterator

Heh. Months of nothing, I cut a release in the middle of the night, then immediately add new code. What I am doing? Anyway, Mango now contains a

public static java.util.Iterator TransformIterator(
    java.util.Iterator iterator,
    UnaryFunction transform
)

A TransformIterator applies a UnaryFunction to each element in the sequence, returning the function result at each step.

Say you have a list of some complex type, and you want to find on by name. You could (caution! trivial example follows)

Iterator i = list.iterator();
while(i.hasNext()) {
  MyComplexObject mco = (MyComplexObject)i.next();
  if(mco.GetName().equals(theSearchName))
    .. do something
}
// did I find it or not?
// might have to check a state variable here to work it out
// anyway - do whatever the right thing is here

or you could

MyComplexObject mco = (MyComplexObject)Mango.find(
                Mango.TransformIterator(
                    list.iterator(),
                    Adapt.ArgumentMethod("GetName")),
                theSearchName);
if(mco != null)
   ... found!
else
   ... not

Of course, you could also use Mango.findIf with a Predicate if that looks nicer to you. Or any one of a dozen other ways.

I grant that (MyComplexObject)find(Mango.TransformIterator(list.iterator(), Adapt.ArgumentMethod("GetName"), theSearchName); looks like a mouthful, and doesn’t appear especially Javay. However, the real power of this stuff isn’t in contrived little examples like this, it’s in the ability to build Predicate and UnaryFunction stacks at runtime.

Let’s say you want to search your MyComplexObject space on several variables. You could do it the conventional way, with lots of loops and if ladders and what not. Or you build a single Predicate object at runtime which combines all the tests together using Mango.And, Mango.Or and friends, apply Mango.findIf or whatever, and it all comes down to almost no code at all.

And then your boss wants a new search term. Predicates make that easy as pie.


Tagged code, mango, java, ranges, iterators, and fp


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired



Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired


Jez Higgins

Freelance software grandad
software created
extended or repaired