How does the Java 'for each' loop work?

2018-12-30 23:26发布

Consider:

List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
    System.out.println(item);
}

What would the equivalent for loop look like without using the for each syntax?

26条回答
不流泪的眼
2楼-- · 2018-12-30 23:41

An alternative to forEach in order to avoid your "for each":

List<String> someList = new ArrayList<String>();

Variant 1 (plain):

someList.stream().forEach(listItem -> {
    System.out.println(listItem);
});

Variant 2 (parallel execution (faster)):

someList.parallelStream().forEach(listItem -> {
    System.out.println(listItem);
});
查看更多
残风、尘缘若梦
3楼-- · 2018-12-30 23:43

In Java 8, they introduced forEach. Using it List, Maps can be looped.

Loop a List using for each

List<String> someList = new ArrayList<String>();
someList.add("A");
someList.add("B");
someList.add("C");

someList.forEach(listItem -> System.out.println(listItem))

or

someList.forEach(listItem-> {
     System.out.println(listItem); 
});

Loop a Map using for each

Map<String, String> mapList = new HashMap<>();
    mapList.put("Key1", "Value1");
    mapList.put("Key2", "Value2");
    mapList.put("Key3", "Value3");

mapList.forEach((key,value)->System.out.println("Key: " + key + " Value : " + value));

or

mapList.forEach((key,value)->{
    System.out.println("Key : " + key + " Value : " + value);
});
查看更多
高级女魔头
4楼-- · 2018-12-30 23:44

Here's an equivalent expression.

for(Iterator<String> sit = someList.iterator(); sit.hasNext(); ) {
    System.out.println(sit.next());
}
查看更多
公子世无双
5楼-- · 2018-12-30 23:45
public static Boolean Add_Tag(int totalsize)
{ List<String> fullst = new ArrayList<String>();
            for(int k=0;k<totalsize;k++)
            {
              fullst.addAll();
            }
}
查看更多
零度萤火
6楼-- · 2018-12-30 23:46
for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
    String item = i.next();
    System.out.println(item);
}

Note that if you need to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for ( : ) idiom, since the actual iterator is merely inferred.

As was noted by Denis Bueno, this code works for any object that implements the Iterable interface.

Also, if the right-hand side of the for (:) idiom is an array rather than an Iterable object, the internal code uses an int index counter and checks against array.length instead. See the Java Language Specification.

查看更多
弹指情弦暗扣
7楼-- · 2018-12-30 23:47

The Java "for-each" loop construct will allow iteration over two types of objects:

  • T[] (arrays of any type)
  • java.lang.Iterable<T>

The Iterable<T> interface has only one method: Iterator<T> iterator(). This works on objects of type Collection<T> because the Collection<T> interface extends Iterable<T>.

查看更多
登录 后发表回答