常见的Strean流模型的使用方式

在Java 8中,得益于Lambda所带来的函数式编程,引入了一个全新的Stream概念,用于解决已有集合类库既有的弊端,流式思想类似于工厂车间的“生产流水线”。下面我们看看Stream流的几种常见的使用方式和示例。
1.forEach
逐个处理。

void forEach(Consumer<? super T> action);
//打印所有元素
String[] arr = {"张翠山", "张三丰", "张无忌", "马蓉", "王宝强"};
        //将数组转换成stream
        Stream<String> arr1 = Stream.of(arr);
        //对数组进行过滤并且打印
        arr1.forEach(name->System.out.println(name));

2.filter
过滤

Stream<T> filter(Predicate<? super T> predicate);
String[] arr = {"张翠山", "张三丰", "张无忌", "马蓉", "王宝强"};
 //将数组转换成stream
 Stream<String> arr1 = Stream.of(arr);
 //对数组进行过滤并且打印
 arr1.filter((String name)->{return name.startsWith("张");})
         .forEach(name->System.out.println(name));

3.map
映射

<R> Stream<R> map(Function<? super T, ? extends R> mapper);
String[] str = {"5", "8", "1", "3", "2"};
Stream<String> str1 = Stream.of(str);
//调用map,map中是Function接口,在判断大于2的个数
str1.map((String s) -> {return Integer.parseInt(s);})
        .forEach(i->System.out.println(i));

4.count
统计个数

//统计字符串中大于2的个数
String[] str = {"5", "8", "1", "3", "2"};
//转换成stream流
Stream<String> str1 = Stream.of(str);
//调用map,map中是Function接口,在判断大于2的个数
long count = str1.map((String s) -> {return Integer.parseInt(s);})
           .filter((Integer i) -> {return i > 2;}).count();

5.limit
截取

String[] arr = {"a","b","c","d","e"};
//取出前三个元素
 Stream<String> limit = Stream.of(arr).limit(3);

6.skip
跳过
使用示例:

String[] arr2 = {"喜羊羊", "美羊羊", "慢羊羊", "灰太狼","红太狼"};
//跳过前三个元素
Stream<String> skip = Stream.of(arr2).skip(3);

7.concat
拼接

static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)

使用示例:

Stream<String> stream1 = Stream.of("Hello");;
Stream<String> stream2 = Stream.of("World");
//将两个stream拼接起来
Stream<String> concat1 = Stream.concat(stream1, stream2);
concat1.forEach(s->System.out.println(s));

运行结果:HelloWorld

没有更多推荐了,返回首页