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

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));
主站蜘蛛池模板: 曲周县| 喜德县| 黄冈市| 隆尧县| 兰西县| 汉沽区| 武清区| 永福县| 拉孜县| 南郑县| 浠水县| 天全县| 思南县| 伊通| 通州市| 哈尔滨市| 舒兰市| 略阳县| 招远市| 辛集市| 郎溪县| 拉萨市| 怀宁县| 荃湾区| 高邮市| 同仁县| 静乐县| 滁州市| 南阳市| 尖扎县| 拉孜县| 芷江| 鞍山市| 大同市| 谷城县| 奎屯市| 永和县| 长汀县| 改则县| 沧源| 右玉县|