官术网_书友最值得收藏!

The forEach method for a collection

Starting with Java 8, we can invoke the forEach method on a collection and iterate through the contents of the collection. Let's compare the 7 and 8 versions of iterating over an array list of strings.

The following code, which is from Jave 7, fetches individual fruit names from the fruits list and prints it to the console:


List<String> fruits = Arrays.asList("Apples", "Oranges", "Bananas",
"Pears");
for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}

A second alternative that you can use is as follows:

for (String fruit : fruits ){
System.out.println(fruit);
}

The example shown here does the same thing in Java 8 using lambda expressions:

fruits.forEach(i -> System.out.println(i));
主站蜘蛛池模板: 丽水市| 罗定市| 乌兰县| 紫金县| 金平| 通化县| 登封市| 海南省| 苏尼特左旗| 屏边| 鄯善县| 五寨县| 门头沟区| 凤山市| 吴川市| 达州市| 长垣县| 安陆市| 沈丘县| 浦城县| 公主岭市| 濉溪县| 景宁| 丰都县| 辽宁省| 革吉县| 吉安市| 清河县| 定安县| 巫山县| 德惠市| 锦屏县| 明光市| 潮安县| 安西县| 湖南省| 德保县| 泾阳县| 峨山| 达拉特旗| 筠连县|