Can I write “foreach” functions in Java?

In PHP, you can do foreach ($array as $key = > $value) {/ / code. Can you create a function in Java to execute foreach (arr, function (key, value) {/ / code});?

I'm not very good at Java For a function to work, it must accept all data types In addition, I'm not sure if callback functions can be used in Java

Attachment: "impossible" is a valid answer, thank you!

Solution

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 also applies to other courses

UPDATE

When traversing a list (array or linked list), the index will be an index You will need to use alternate integers to save 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 the map (key and value based structure), you should use the method described by @ lukaseder (adjust 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...
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>