首页 > 其他 > 详细

jdk1.8 -- stream 的使用

时间:2019-05-30 10:12:30      阅读:133      评论:0      收藏:0      [点我收藏+]

一.stream介绍

  stream 是jdk 一个加强的api操作,翻译过来就是流的意思,主要是对Collection 集合的一些操作,流一但生成就会有方向性,类似于自来水管的水流一样,不可以重复使用。

  stream 中的操作有filter map limt sorted collect

二.生成stream的方式

  集合.stream(); − 为集合创建串行流

  集合.parallelStream()  − 为集合创建并行流

三.stream中的操作

 1.filter 操作

public class StreamTest {
    public static void main(String[] args) {
        List<Apple> apples =Arrays.asList(
                            new Apple("green", 150),new Apple("red", 170),new Apple("yellow", 190),
                            new Apple("blue", 210));
        //filter 操作是将流按自定义条件进行过虑  返回过虑后符合规则的stream
        Stream<Apple> filter = apples.stream().filter(a -> a.getWeight()>200);
        
    }
}

 2.map操作

public class StreamTest {
    public static void main(String[] args) {
        List<Apple> apples =Arrays.asList(
                            new Apple("green", 150),new Apple("red", 170),new Apple("yellow", 190),
                            new Apple("blue", 210));
        
        //map 操作是将stream 通过map操作返回符合map规则的stream
     // map 与filter 的区别
     //  map是一个Function 即传和一个 T 返回一个 R 类似于get操作 如果流中有元素符合map的操作条件,注会将得到的R存入到stream中,会改变流中存储的元素
     //  filter 是一个 Predicate 即传入一个 T 返回的是bollean 是用来做判断的,如果流中的某个元素符合filter的条件,就会存入到stream中,不符合的将被过滤掉
Stream
<String> map = apples.stream().map(Apple::getColor); } }

 3.limt

public class StreamTest {
    public static void main(String[] args) {
        List<Apple> apples =Arrays.asList(
                            new Apple("green", 150),new Apple("red", 170),new Apple("yellow", 190),
                            new Apple("blue", 210));
     //取流中多少个元素
        Stream<Apple> limit = apples.stream().limit(2);
    }
}

4.sort collect 

public class StreamTest {
    public static void main(String[] args) {
        List<Apple> apples =Arrays.asList(
                            new Apple("green", 150),new Apple("red", 170),new Apple("yellow", 190),
                            new Apple("blue", 210));
        
       //sorted 是按颜色的字母顺序来排序
     //collect 是将流转换成相对应的集合
List
<Apple> collect = apples.stream().sorted(Comparator.comparing(Apple::getColor)).collect(Collectors.toList()); } }

四.stream 的并行操作

  将集合转换成并行流后之后,其它操作与串行流相同

  并行流可以通过将程序休眠,通过jconsole 工具查看

 

jdk1.8 -- stream 的使用

原文:https://www.cnblogs.com/MrRightZhao/p/10947834.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!