个性化阅读
专注于IT技术分析

Java forEach循环

本文概述

Java提供了一个新的forEach()方法来迭代元素。它在Iterable和Stream接口中定义。这是Iterable接口中定义的默认方法。扩展Iterable接口的集合类可以使用forEach循环来迭代元素。

该方法采用单个参数, 该参数是功能接口。因此, 你可以将lambda表达式作为参数传递。


迭代接口中的forEach()签名

default void forEach(Consumer<super T>action)

Java 8 forEach()示例1

import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
	public static void main(String[] args) {
		List<String> gamesList = new ArrayList<String>();
		gamesList.add("Football");
		gamesList.add("Cricket");
		gamesList.add("Chess");
		gamesList.add("Hocky");
		System.out.println("------------Iterating by passing lambda expression--------------");
		gamesList.forEach(games -> System.out.println(games));
		
	}
}

输出:

------------Iterating by passing lambda expression--------------
Football
Cricket
Chess
Hocky

Java 8 forEach()示例2

import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
	public static void main(String[] args) {
		List<String> gamesList = new ArrayList<String>();
		gamesList.add("Football");
		gamesList.add("Cricket");
		gamesList.add("Chess");
		gamesList.add("Hocky");
		System.out.println("------------Iterating by passing method reference---------------");
		gamesList.forEach(System.out::println);
	}
}

输出:

------------Iterating by passing method reference---------------
Football
Cricket
Chess
Hocky

Java Stream forEachOrdered()方法

Java与forEach()方法一起, 为EachOrdered()提供了另一种方法。它用于按流指定的顺序迭代元素。

Singnature:

void forEachOrdered(Consumer<? super T> action)

Java Stream forEachOrdered()方法示例

import java.util.ArrayList;
import java.util.List;
public class ForEachOrderedExample {
	public static void main(String[] args) {
		List<String> gamesList = new ArrayList<String>();
		gamesList.add("Football");
		gamesList.add("Cricket");
		gamesList.add("Chess");
		gamesList.add("Hocky");
		System.out.println("------------Iterating by passing lambda expression---------------");
		gamesList.stream().forEachOrdered(games -> System.out.println(games));
		System.out.println("------------Iterating by passing method reference---------------");
		gamesList.stream().forEachOrdered(System.out::println);
	}

}

输出:

------------Iterating by passing lambda expression---------------
Football
Cricket
Chess
Hocky
------------Iterating by passing method reference---------------
Football
Cricket
Chess
Hocky
赞(0)
未经允许不得转载:srcmini » Java forEach循环

评论 抢沙发

评论前必须登录!