使用流

作者: 上海马超23 | 来源:发表于2017-07-14 22:41 被阅读0次

    筛选和切片

    筛选

    // 筛选蔬菜
    List<Dish> vegetarianMenu = menu.stream().filter(Dish::isVegetarian).collect(toList());
    

    排重

    // 列出所有偶数排重
    numbers.stream().filter(i -> i%2 ==0).distinct().forEach(...);
    

    截断

    // 取前3个成员
    menu.stream().limit(3).collect(...);
    

    跳过元素

    // 跳过前2个成员
    menu.stream().skip(2).collect(...);
    

    映射

    对流中每一个元素应用函数

    // 提取每道菜名称的长度
    menu.stream().map(Dish::getName).map(String::length).collect(...);
    

    流的扁平化

    words.stream().map(w->w.split("") // 单词转换成字母构成的数组
      .flatMap(Arrays::stream) // 扁平化 (相当于把数组拆成一个个元素,没有数组和数组之间结构之分)
      .distinct().collect(...);
    

    查找和匹配

    至少匹配一个元素

    // 集合里有一个元素都满足,就返回true
    if (menu.stream().anyMatch(Dish::isVegetarian)) {
      ...
    }
    

    匹配所有元素

    isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000);
    
    // 相对的,确保流中没有任何元素与给定的谓词匹配
    isHealthy = menu.stream().noneMatch(d -> d.getCalories() >= 1000);
    

    查找元素

    // 找到流中的任意一道素菜
    Optional<Dish> dish = menu.stream().filter(Dish::isVegetarian).findAny();
    

    查找第一个元素

    // findFirst在并行上限制更多,findAny限制少,前提是你不关心返回的元素是哪个
    someNumbers.stream().filter(x->x%3 ==0).findFirst();
    

    归约

    求和

    numbers.stream().reduce(0, (a, b) -> a+b);
    

    最大值和最小值

    numbers.stream().reduce((x,y) -> x<y?x:y);
    

    数值流

    原始类型流特化

    // 数值流
    // mapToInt将Stream<Integer>转换成IntStrem,就可以调用特有的sum等方法了
    menu.stream().mapToInt(Dish::getCalories).sum();
    
    // boxed转化回对象流
    intStream().boxed();
    

    构建流

    由值创建流

    Stream<String> stream = Stream.of("...", "...");
    

    由数组创建流

    // int数组直接转换成IntStream()
    Arrays.stream(numbers).sum();
    

    由文件生成流

    Stream<String> lines = Files.lines(Paths.get("data.txt"),Charset.defaultCharset());
    

    相关文章

      网友评论

          本文标题:使用流

          本文链接:https://www.haomeiwen.com/subject/gfwohxtx.html