Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Collection in Java

Consider a problem, in which I'm developing a tree like Collection.

One of the main functionality of my Collection is to trace all the stored items one by one and then call a given function for each item until a given criteria has been met (lazy Collection).

So the function should have the following signatures:

void Trace(function func, criteria crit)
{
    item i = firstItem();
    while (i != endItem())
    {
        i = nextItem();
        func(i);
        if (crit(i))
            return;
    }
}

in C++ function pointers can be used for func and crit.
in C#, yield keyword is exactly the solution to this problem, I believe.

How can I get the same thing in Java?

like image 831
MBZ Avatar asked Dec 28 '12 01:12

MBZ


2 Answers

In Java, you would pass references to objects of classes that implement applicable functions, or use Commons Collections instead:

  • Use Predicate implementations for the crit part.
  • Use Closure implementations for the func part.

For example:

Closure c = new Closure() {
    public void execute(Object obj) {
        ...
    }
};

Predicate p = new Predicate() {
    public boolean evaluate(Object obj) {
        ...
    }
}

Trace(c, p);
like image 79
Isaac Avatar answered Oct 05 '22 23:10

Isaac


What you're looking for here is the Strategy design pattern.

The goal of this pattern to to abstract the implementation of an algorithm into a Strategy object. Here, your algorithms are the func and crit functions that you're looking to pass in.

So, you'd have an interface called something like TraceStrategy. You'd then pass implementations of this interface in to your collection. Your code would then look something like

void Trace(TraceStrategy traceStrategy)
{
    item i = firstItem();
    while (i != endItem())
    {
        i = nextItem();
        traceStrategy.func(i);
        if (traceStrategy.crit(i))
            return;
    }
}

and

interface TraceStrategy {
   public boolean crit(item i);

   public void func(item i);
}

You'd probably want to make this generic, so that you weren't tied to item... but you get the idea.

like image 24
Dancrumb Avatar answered Oct 05 '22 23:10

Dancrumb