Is it possible to write a "foreach" function in Java?
In PHP you can do foreach($array as $key=>$value){//codes
. Is it possible to create a function in Java to do foreach(arr,function(key,value){//codes});
?
I am not very good at Java. For a function to work, it must accept all data types. Also, I'm not sure if callback functions can be used in Java.
PS "Impossible" is the correct answer, thanks!
source to share
Yes, you can:
List<String> ls = new ArrayList();
ls.add("Hello");
ls.add("world");
//your foreach sentence
for(String s : ls) {
System.out.println(s);
}
This works with other classes as well.
UPDATE
When traversing a list (array or linked list), the index will be the index. You need to use an alternate integer to store the index:
List<String> ls = new ArrayList();
ls.add("Hello");
ls.add("world");
//your foreach sentence
int index = 0;
for(String s : ls) {
System.out.println("index: " + index);
System.out.println(s);
//put your logic here...
//at the end, update the index manually
index++;
}
If you need to traverse a map (key value based structure), then you should use the method described by @LukasEder (adapting his code):
Map<K, V> array = new HashMap<K, V>();
for (Entry<K, V> entry : array.entrySet()) {
// You have to explicitly call your callback. There is no "callback-syntax"
// to the Java "foreach" loop
System.out.println("key: " + entry.getKey());
System.out.println("value: " + entry.getValue());
//put your logic here...
}
source to share
The other answers have explained how the "extended for loop" syntax works. And that may very well be what you need.
But I want to answer the question you actually asked:
Is it possible to create a function in Java:
foreach(arr,function(key,value){//codes});
As written, it will be a function (or method) that takes another function as a parameter. This is not possible in Java as currently defined. Java does not allow functions (or methods) to be treated as first class objects. They cannot be passed as arguments. The closest you can find (current) Java is to create an interface Function
like this:
public interface Function {
public void fun(Object arg1, Object arg2);
}
and use it like this:
Object[] arr = ...
foreach (arr, new Function() {
public void fun (Object key, Object value) {
// do stuff
}});
(I'm talking about how a PHP array is more like a Java HashMap than a Java array. It affects how you implement things like this ... but it distracts from the main point I'm trying to do.)
At some point in the future Java will be extended to support first-class functions / closures / lambdas or something similar. This feature was assigned for Java 7 for a while, but had to be delayed in the interest of getting Java 7.
UPDATE . It is now clear that support for lambda will be in Java 8. This new feature was uploaded at the beginning of the release.
source to share
Since PHP arrays are actually associative arrays, the closest to your code would be using Java Map
:
Map<K, V> array = new HashMap<K, V>();
for (Entry<K, V> entry : array.entrySet()) {
// You have to explicitly call your callback. There is no "callback-syntax"
// to the Java "foreach" loop
MyClass.myMethod(entry.getKey(), entry.getValue());
}
Replace <K>
with <V>
more specific types, eg. Map<String, String>
, or Map<Integer, String>
etc.
If you are using true (indexed) arrays, you cannot write a foreach loop to access the index. You will have to resort to an indexed loop:
// Using Java arrays
String[] array = { "a", "b", "c" };
for (int i = 0; i < array.length; i++) {
MyClass.myMethod(i, array[i]);
}
// Using Java Lists
List<String> list = Arrays.asList("a", "b", "c");
for (int i = 0; i < list.size(); i++) {
MyClass.myMethod(i, list.get(i));
}
source to share
Yes. If you are iterating over an array or an object that implements Iterable, then the following syntax will work:
SomeType someValue=null;
for (someValue : setOfValues) {
...
}
For example:
Map<String,String> colors=new HashMap<String,String>();
colors.put("r","red");
colors.put("g","green");
colors.put("b","blue");
for (String code : colors.keySet()) {
process(code, colors.get(code));
}
source to share
Yes, you can, as long as the collection you are iterating over implements Iterable
. So, you can have something like this:
Map<String, Object> map = new HashMap<String, Object>();
...
for (String str : map.keySet())
{
System.out.println(str);
}
It should create HashMap
which is a collection of key values. If you just want to iterate over normal collections like Lists
and Arrays
, you can do something like this:
List<String> strings = new ArrayList<String>();
....
for(String str : strings)
{
System.out.println(str);
}
source to share
He called it "extended for the cycle"
screencast: http://www.youtube.com/watch?v=w41D0V-BnKQ
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html
source to share