There are two main changes to this code to make it work in Java. First, you will need to replace STL style iterators with Java style iterators, which, fortunately, aren't too complicated. Secondly, you will have to change the use of a function pointer or functor parameter with an object of a different type, since Java does not support function pointers.
In Java, iterators are heavier than in C ++ and encapsulate the entire range that they go through, not just the beginning or end of that range. Using the Java iterator, you use the .next () and .hasNext () methods to move around the range.
As for the function parameter, you probably need to create your own interface representing some object that can be called a function. For instance:
public interface Operation<T> { void apply(T argument); }
This interface is a typical parameter for some type T, which indicates the type of argument, and then exports a function called apply () that applies this function.
Given this, a simple but naive way of for_each replication would be to write
public static <T> forEach(Iterator<T> itr, Operation<T> op) { while (itr.hasNext()) op.apply(itr.next()); }
The reason I say it is naive is that it does not use restricted wildcards correctly in order to expand the scope where it can be used. A more suitable version, more friendly to Java, would be:
public static <T> forEach(Iterator<T> itr, Operation<? super T> op) { while (itr.hasNext()) op.apply(itr.next()); }
Consult a link to Java Genetics for why this works.
Hope this helps!