写在前面
在这里,我们将会学习怎么利用java8 快速的打印出需要打印的元素
利用stream打印元素
在Java中,有三种不同的方法来打印Java 8中的Stream元素。这三种不同方式的名称如下:
Stream 的 forEach()方法
Stream的 println()方法和collect()方法
Stream的 peek()方法
我们将在java 8中逐一看到打印流元素的三种方法……
这个方法的语法如下所示:
void forEach(Consumer <? super T > consumer);
这里,Consumer是一个接口,T是元素类型
示例:不用lambda表达式
import java.util.stream.*;
public class PrintStreamElementByForeachMethod {
public static void main(String[] args) {
// Here of() method of Stream interface is used to get the stream
Stream stm = Stream.of("Java", "is", "a", "programming", "language");
// we are printing the stream by using forEach() method
stm.forEach(stm1 -> System.out.println(stm1));
}
}
输出
Java
is
a
programming
language
示例:简写lambda表达式
import java.util.stream.*;
public class PrintStreamElementByForeachMethod {
public static void main(String[] args) {
// Here of() method of Stream interface is used to get the stream
Stream stm = Stream.of("Java", "is", "a", "programming", "language");
// we are printing the stream by using forEach() method
stm.forEach(System.out::println);
}
}
输出
Java
is
a
programming
language
println()与collect()方法的语法
System.out.println(Stream_object.collect(Collectors.toList()));
示例
import java.util.stream.*;
public class PrintStreamElementByForeachMethod {
public static void main(String[] args) {
// Here of() method of Stream interface is used to get the stream
Stream stm = Stream.of("Java", "is", "a", "programming", "language");
// we are printing the stream by using forEach() method
stm.forEach(System.out::println);
}
}
输出
[Java, is, a, programming, language]
Stream peek(Consumer <? super T> consumer);
示例
import java.util.stream.*;
public class PrintStreamElementByPeekMethod {
public static void main(String[] args) {
// Here of() method of Stream interface is used to get the stream
Stream stm = Stream.of("Java", "is", "a", "programming", "language");
// we are printing the stream by using peek() method
// and it provides the facility count() method to terminate
stm.peek(stm1 -> System.out.println(stm1)).count();
}
}
输出
Java
is
a
programming
language