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

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));
主站蜘蛛池模板: 宁波市| 岳普湖县| 遂宁市| 旌德县| 清原| 施甸县| 巴南区| 河曲县| 昂仁县| 讷河市| 临漳县| 河南省| 平塘县| 铁力市| 汶川县| 阜平县| 磐安县| 清涧县| 隆昌县| 肥城市| 武乡县| 同仁县| 泗水县| 清徐县| 西乡县| 修武县| 石嘴山市| 周宁县| 灵丘县| 马山县| 定远县| 额尔古纳市| 东乡县| 长岛县| 西贡区| 松溪县| 精河县| 丽水市| 焉耆| 荔波县| 丽江市|