考虑:

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

如果不使用for each语法,等价的for循环会是什么样子?


当前回答

如JLS中所定义的,每个循环的a可以有两种形式:

如果表达式类型是Iterable的子类型,则转换为:List<String>someList=newArrayList<String>();someList.add(“苹果”);someList.add(“球”);for(字符串项:someList){System.out.println(项);}//翻译为:for(Iterator<String>stringIterator=someList.iiterator();stringIterator.hasNext();){字符串项=stringIterator.next();System.out.println(项);}如果表达式必须具有数组类型T[],则:String[]someArray=新字符串[2];someArray[0]=“苹果”;someArray[1]=“球”;for(字符串项2:someArray){系统输出打印(第2项);}//翻译为:for(int i=0;i<someArray.length;i++){字符串item2=someArray[i];系统输出打印(第2项);}

Java8已经引入了一些流,这些流在适当大小的数据集中通常表现得更好。我们可以将它们用作:

someList.stream().forEach(System.out::println);
Arrays.stream(someArray).forEach(System.out::println);

其他回答

它看起来像这样。非常粗糙。

for (Iterator<String> i = someList.iterator(); i.hasNext(); )
        System.out.println(i.next());

Sun文档中对每一项都有很好的描述。

Java“for each”循环构造将允许对两种类型的对象进行迭代:

T[](任何类型的数组)java.lang.Iterable<T>

Iterable<T>接口只有一个方法:Iterator<T>迭代器()。这对Collection<T>类型的对象有效,因为Collection<T<接口扩展了Iterable<T>。

使用forEach:

int[] numbers = {1,2,3,4,5};

Arrays.stream(numbers).forEach(System.out::println);

答复:

1
2
3
4
5

The process finished with exit code 0

PS:您需要一个Array(int[]数字),然后导入java.util.Arrays;

forEach的替代方案,以避免“for each”:

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

变体1(普通):

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

变体2(并行执行(更快)):

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

在Java8中,他们引入了forEach。使用它列表,可以循环地图。

使用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); 
});

使用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);
});