Freelance software grandad
software created
extended or repaired
Follow me on Mastodon
Applications, Libraries, Code
Talks & Presentations
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 hereor you could
MyComplexObject mco = (MyComplexObject)Mango.find( Mango.TransformIterator(list.iterator(), Adapt.ArgumentMethod("GetName"), theSearchName); if(mco != null) ... found! else ... notOf 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 are runtime. Lets 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. Then 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.
Freelance software grandad
software created
extended or repaired
Follow me on Mastodon
Applications, Libraries, Code
Talks & Presentations