Reputation: 9015
I'm new to Java and wondering how I could go about implementing a method like Ruby's .each
to make iterating over classes like Arrays and Lists easier?
Upvotes: 1
Views: 1466
Reputation: 2724
Consider the command pattern:
http://en.wikipedia.org/wiki/Command_pattern#Java
Upvotes: 0
Reputation: 10007
While it is true that it's slightly awkward to achieve in standard Java, a couple of the popular libraries (that you may even already be using) offer a Predicate
interface that spares you the bulk of writing that much, at least. The great thing is that they also offer thoroughly-tested, proven helper classes that mean you don't have to write the iteration code.
Check out Google Guava's Iterables class - you can do things like filter()
, findIf()
and removeIf()
. If used well, these methods can make for extremely readable results.
Apache's Commons Collections offers something similar in CollectionUtils. Methods like find()
, filter()
and select()
all take a Predicate
.
Google Guava also goes further and gives you the Predicates
helper which has a whole load of canned Predicate
instances - things like isNull
, containsPattern
and isInstanceOf
.
Check them out if you want to avoid reinventing the wheel for this stuff.
Upvotes: 4
Reputation: 7290
It gets ugly due to the lack of closures, until Java 8, but here it is:
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class EachTest {
interface ItemProcessor<T>{
void process(T item);
}
static <T> void each(Collection<T> collection, ItemProcessor<T> processor){
for (T item: collection){
processor.process(item);
}
}
public static void main(String[] args) {
List<String> list=Arrays.asList(new String("foo"),"bar");
EachTest.<String>each(list,new ItemProcessor<String>() {
@Override
public void process(String item) {
System.out.println(item);
}
});
}
}
I think in Java 8, it will be (but don't quote me on that):
public static void main(String[] args) {
List<String> list=Arrays.asList(new String("foo"),"bar");
EachTest.<String>each(list,String item=>System.out.println(item));
}
Upvotes: 1
Reputation: 26492
You can't make an each function, like Ruby has, since Java doesn't accept blocks as parameters like Ruby does. You could use an interface and provide an anonymous class definition, but that's way more complicated than just using Java's for each construct. To do for each in Java, you can do something like the following:
String[] myStrings = { "a", "b", "c" };
for (String str : myStrings) {
// Do something with each String value.
System.out.println(str);
}
Upvotes: 1