Stream API的t akewhile() 方法接受所有值,直到谓词 返回false为止,而Stream API的dropWhile()方法丢弃所有值,直到它与谓词匹配为止。如果对流进行了排序,则takewhile()方法将返回一个流,该流由从该流中获取的,与谓词 匹配的元素的最长前缀 组成,而dropWhile()方法将在匹配谓词后返回剩余的流。如果流是无序的,则takewhile()方法返回由从与给定谓词匹配的流中提取的元素子集组成的流,而dropWhile()方法在删除与给定谓词匹配的元素子集后返回由流的其余元素组成的流。
takeWhile()
default Stream<T> takeWhile(Predicate<? super T> predicate)
import java.util.stream.Stream; public class TakeWhileMethodTest { public static void main(String args[]) { Stream.of("India", "Australia", "Newzealand", "", "South Africa", "England") .takeWhile(o->!o.isEmpty()) .forEach(System.out::print); } }
输出结果
IndiaAustraliaNewzealand
dropWhile()
default Stream<T> dropWhile(Predicate<? super T> predicate)
import java.util.stream.Stream; public class DropWhileMethodTest { public static void main(String args[]) { Stream.of("India", "Australia", "Newzealand", "", "England", "Srilanka") .dropWhile(o->!o.isEmpty()) .forEach(System.out::print); System.out.println(); Stream.of("India", "", "Australia", "", "England", "Srilanka") .dropWhile(o->!o.isEmpty()) .forEach(System.out::print); } }
输出结果
EnglandSrilanka AustraliaEnglandSrilanka