在处理集合时,我们通常会迭代遍历他的元素,并在每个元素上执行某项操作。例如,假设我们想要对某本书中的所有长单词进行计数。首先,将所有单词放到一个列表中:
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.io.IOException;
import java.nio.file.*;
public class diedailiu {
public static void main(String[] args) throws IOException {
String contents=new String(Files.readAllBytes(Paths.get("./alice.txt")),StandardCharsets.UTF_8);
List<String> words=Arrays.asList(contents.split("\\PL+"));
long count=0;
for(String w:words) {
if(w.length()>12)count++;
}
System.out.println(count);
count=words.stream().filter(w->w.length()>12).count();
System.out.println(count);
count=words.stream().filter(w->w.length()>12).count();
System.out.println(count);
count=words.parallelStream().filter(w->w.length()>12).count();
System.out.println(count);
}
}