map与flatMap
flatMap参数必须是一个个流,作用是将多个流合并成一个流
package chapter1; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.stream.Stream; public class IO { public static void main(String[] args) throws IOException { long uniqueWords = 0; try (Stream<String> lines = Files.lines(Paths.get("src/main/resources/data.txt"))) { /** map */ // Stream<String[]> stream1 = lines.map(line -> line.split(" ")); /** flatMap */ Stream<String> stringStream = lines.flatMap(line -> { Stream<String> stream = Arrays.stream(line.split(" ")); return stream; }); uniqueWords = stringStream.distinct().count(); } System.out.println(uniqueWords);//4 } }
data.txt:
a b b c
c
d a