JAVA 8 Stream小计

import staticjava

静态导入,方便使用;常常要导入的数组

java.util.stream.Collectors.toList

filter函数

接受Lambda,从流中 除某些元素code


mapip

接受一个Lambda,这个函数会被应用到每一个元素上,并将其映 射成一个新的元素get


limit数学

截断流,使其元素不 过给定数量hash


countit

返回流中元素的个数。 collect 将流转换为其余形式。io


forEach

消费流中的每一个元素并对其应用Lambda


请注意,和迭代器相似,流只能遍历一次。遍历完以后,咱们就说这个流已经被消费掉了


distinct

返回一个元素各异(根据流所生成元素的hashCode和equals方法实现)的流


skip


Arrays.stream()

能够接受 一个数组并 生一个流

String[] arrayOfWords = {"Goodbye", "World"}; 
Stream<String> streamOfwords = Arrays.stream(arrayOfWords);
words.stream()
     .map(word -> word.split(""))
     .map(Arrays::stream)//让每一个数组变成一个单独的流 
     .distinct()
     .collect(toList());

flatMap

把一个流中的每一个值都换成另外一个流,而后把全部的流 接 起来成为一个流。

List<String> uniqueCharacters =
    words.stream()
         .map(w -> w.split(""))
         .flatMap(Arrays::stream)
         .distinct()
         .collect(Collectors.toList());

anyMatch

“流中是否有一个元素能 配给定的谓词”

if(menu.stream().anyMatch(Dish::isVegetarian)){
    System.out.println("The menu is (somewhat) vegetarian friendly!!");
}

allMatch

但它会看看流中的元素是否都能匹配给定的谓词

boolean isHealthy = menu.stream()
                            .allMatch(d -> d.getCalories() < 1000);
//全部菜的热量都低于1000卡路里

noneMatch

它能够确保流中没有任何元素与给定的谓词匹配

boolean isHealthy = menu.stream()
                            .noneMatch(d -> d.getCalories() >= 1000);

findAny

将返回当前流中的任意元素。

Optional<Dish> dish =
        menu.stream()
            .filter(Dish::isVegetarian)
            .findAny();

findFirst

找到第一个元素

List<Integer> someNumbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> firstSquareDivisibleByThree =
    someNumbers.stream()
                .map(x -> x * x)
                .filter(x -> x % 3 == 0)
                .findFirst(); // 9

reduce归约

reduce接受两个参数:

  • 一个初始值,这里是0;

  • 一个BinaryOperator<T>来将两个元素结合起来 生一个新值

int product = numbers.stream().reduce(1, (a, b) -> a * b);

max&min

//max
Optional<Integer> max = numbers.stream().reduce(Integer::max);
//min
Optional<Integer> min = numbers.stream().reduce(Integer::min);

将流转换为特化版本的经常使用方法是mapToInt、mapToDouble和mapToLong。

int calories = menu.stream()
                    .mapToInt(Dish::getCalories)//返回一个IntStrean
                    .sum();

IntStream还支持其余的方便方法,如max、min、average等。

Optional

Optional<T>类(java.util.Optional)是一个容器类,表明一个值存在或不存在。


数值范围

IntStream和LongStream的静态方法,帮助生成这种范 : range和rangeClosed。这两个方法都是第一个参数接受起始值,第二个参数接受结束值。相似与数学中的( ] rangeClosed 和[ ) range


empty

获得一个空流

Stream<String> emptyStream = Stream.empty();

数组建立流

使用静态方法Arrays.stream从数组建立一个流

int[] numbers = {2, 3, 5, 7, 11, 13}; int sum = Arrays.stream(numbers).sum();
相关文章
相关标签/搜索