设为首页 加入收藏

TOP

java -- Stream流(四)
2023-07-25 21:30:38 】 浏览:65
Tags:java Stream
的Person对象信息。 Stream.concat(streamOne, streamTwo).forEach(s->System.out.println(s)); } }

运行效果完全一样:

宋远桥
苏星河
洪七公
张二狗
张天爱
张三

函数拼接与终结方法

在上述介绍的各种方法中,凡是返回值仍然为Stream接口的为函数拼接方法,它们支持链式调用;而返回值不再为Stream接口的为终结方法,不再支持链式调用。如下表所示:

方法名 方法作用 方法种类 是否支持链式调用
count 统计个数 终结
forEach 逐一处理 终结
filter 过滤 函数拼接
limit 取用前几个 函数拼接
skip 跳过前几个 函数拼接
concat 组合 函数拼接

Stream流中的结果到集合中

Stream流提供 collect方法,其参数需要一个 java.util.stream.Collector<T,A, R>接口对象来指定收集到哪 种集合中。java.util.stream.Collectors 类提供一些方法,可以作为 Collector`接口的实例:

  • public static Collector<T, ?, List > toList():转换为 List集合。
  • public static Collector<T, ?, Set > toSet():转换为 Set集合。

下面是这两个方法的基本使用代码

public class Test {

    public static void main(String[] args) {
        Stream<String> stream = Stream.of("aa", "bb", "cc");
        //转换为list集合
        List<String> list = stream.collect(Collectors.toList());
        //转换为set集合
        Set<String> set = stream.collect(Collectors.toSet());
        //转换为ArrayList集合
        ArrayList<String> arrayList = stream.collect(Collectors.toCollection(ArrayList::new));
        //转换为HashSet集合
        HashSet<String> hashSet = stream.collect(Collectors.toCollection(HashSet::new));
    }

}

Stream流中的结果到数组中

Stream提供 toArray方法来将结果放到一个数组中,返回值类型是Object[]的:

Object[] toArray();

其使用场景如:

public class Test {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("aa", "bb", "cc");

        Object[] objects = stream.toArray();
        System.out.println(Arrays.toString(objects));

        String[] strings = stream.toArray(String[]::new);
        System.out.println(Arrays.toString(strings));
    }
}
首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Elasticsearch mapping 下一篇一天吃透SpringMVC面试八股文

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目