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

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));
主站蜘蛛池模板: 成都市| 安达市| 西盟| 融水| 京山县| 贵溪市| 永靖县| 靖西县| 海城市| 八宿县| 江都市| 陇川县| 陈巴尔虎旗| 礼泉县| 手游| 莆田市| 辛集市| 宁陵县| 米林县| 宣恩县| 秦安县| 宣化县| 北宁市| 五原县| 汝城县| 梁平县| 砚山县| 古丈县| 阜阳市| 丰城市| 宿州市| 彰化县| 兰坪| 万荣县| 文昌市| 大方县| 宁津县| 松阳县| 乡宁县| 南雄市| 阿尔山市|