filter方法接受一个返回boolean的方法。api
List<Dish> vegetarianMenu=menu.stream().filter(Dish::isVegetarian) .collect(toList());
distinct方法,根据流中元素的hashCode和equals方法。例:数组
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4); numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);
limit(n)方法,该方法会返回一个不超过给定长度的流。函数
若是流是有序的,则最多会返回前n个元素。工具
limit也能够用在无序流上,好比源是一个Set。这种状况下,limit的结果不会以任何顺序排列。code
List<Dish> dishes = menu.stream() .filter(d -> d.getCalories() > 300).limit(3).collect(toList());
skip(n)方法返回一个扔掉了前n个元素的流。若是流中元素不足n个,则返回一个空流。skip方法和limit方法能够当作是相反的操做。对象
流支持map方法,它会接受一个函数做为参数。这个函数会被应用到每一个元素上,并将其映射成一个新的元素。ip
下面的代码,对words中的全部字符串应用String::length方法。字符串
List<String> words = Arrays.asList("Java 8", "Lambdas", "In", "Action"); List<Integer> wordLengths = words.stream().map(String::length).collect(toList());
什么叫扁平化?举个例子:把Stream<Stream< String >> 变成 Steam< String > 就叫扁平化。get
一言以蔽之,flatmap方法让你把一个流中的每一个值都换成另外一个流,而后把全部的流链接起来成为一个流。
List<String> words = Arrays.asList("Java 8", "Lambdas", "In", "Action"); //map函数中每一个字符串都被切割为字符串数组,返回一个字符串数组的流 List<String[]> collect = words.stream() .map(word -> word.split("")) .distinct() .collect(toList()); //Arrays.stram方法接受一个数组返回一个流 String[] arrayOfWords = {"Goodbye", "World"}; Stream<String> streamOfwords = Arrays.stream(arrayOfWords); //第一个map返回一个字符串流,流中的元素是一个个的字符串数组。 //第二个map对每个字符数组应用Arrays.stream函数,因此每个字 //符串数组映射为一个字符串流。 List<Stream<String>> collect1 = words.stream() .map(word -> word.split("")) .map(v -> Arrays.stream(v)) .distinct() .collect(toList()); //第一个map返回一个字符串流,流中的元素是一个个的字符串数组。 //flatMap方法把流中的每一个字符串数组都换成一个流,而后链接它们成 //为一个流 List<String> uniqueCharacters = words.stream() .map(w -> w.split("")) .flatMap(Arrays::stream) .distinct() .collect(Collectors.toList());
另外一个常见的数据处理套路是看看数据集中的某些元素是否匹配一个给定的属性。Stream API经过allMatch、anyMatch、noneMatch、findFirst、findAny方法提供了这样的工具。
注:这些工具方法的返回值都不是流。因此它们是终端操做
if(menu.stream().anyMatch(Dish::isVegetarian)){ System.out.println("The menu is (somewhat) vegetarian friendly!!"); }
//是否全部元素都匹配 boolean isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000); //是否全部元素都 不 匹配 boolean isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000);
findAny方法将返回当前流中的任意元素。
Optional<Dish> dish = menu.stream().filter(Dish::isVegetarian).findAny();
Optional是什么?
List<Integer> someNumbers = Arrays.asList(1, 2, 3, 2, 5); //filter返回一个流,findfirst在该流中找第一个 Optional<Integer> firstSquareDivisibleByThree = someNumbers.stream() .filter(x -> x == 2) .findFirst();
归约:将流中的元素相互结合起来,求一个值。好比学生是元素求分数最高的学生、分数是元素求某位同窗的总分。
//求numbers中全部数值的集合 int product = numbers.stream().reduce(1, (a, b) -> a * b);
一个初始值,这里是0;
一个BinaryOperator
lambda (a, b) -> a + b。
无初始值
reduce还有一个重载的变体,它不接受初始值,可是会返回一个Optional对象:
Optional
该篇对于流的使用,作了简要的笔记。能够知足大多数状况的需求。不要只是看看,不要只是作了笔记。这么好用的api,赶忙用起来吧。