Lamdba optional-stream

不得不说学习起来时间真过得好快啊, 而且什么都不用想,只关注学习就好, 但是时间过得太快,嘿嘿,还有好多没有学习呢, 慢慢来, 棒棒哒

optional

对于NullPointerException相信大家应该都不陌生把,嘿嘿, 一般在没有做判空处理的时候,会抛出NullPointerException异常, 但是有的时候写if…else 代码 , 代码看起来着实难看,下面推荐java9提供的option是如何处理异常的

这样的写法其实和if没有区别,也就是判断是否存在

      Optional<String> optionalS = Optional.empty();
        if (optionalS.isPresent()){
            System.out.println(optionalS.get());     //跟以前的if判断没有什么区别
        }

推荐使用方式 1

optionalS.ifPresent(item-> System.out.println(item));  //推荐判空写法

推荐使用方式 2
Optional.ofNullable(Object)

  Optional<Company> optionalCompany = Optional.ofNullable(company);
  System.out.println(optionalCompany.map(theCompany -> theCompany.getEmployeeList()).orElse(Collections.emptyList()));

当我们在使用stream流的时候会发现我们没有做判空的处理,请问谁帮我们做了? 看看map底层是如何实现的吧 , 返回的对象是optional,使用了Optional.ofNullable() , 我最近在着手阅读源码, 这也是为什么我突然想读源码的原因, 就是想看看优秀的代码是如何编写的.怎么优雅的,哈哈哈哈

  public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
        Objects.requireNonNull(mapper);
        if (!isPresent())
            return empty();
        else {
            return Optional.ofNullable(mapper.apply(value));
        }
    }

optional if else

对于option非常方便的是提供else的方式,在写业务代码的时候也着实方便了很多.if为空则获取的是world.

optionalS.orElse("world");
optionalS.orElseGet(() -> "sadf");

Stream

创建Stream方式

Stream<String> stringStream = Stream.of("1", "2", "3");
String[] stream= new String[]{"1","2","3"};
Stream<String> stream1 = Arrays.stream(stream);
Stream<String> stream2 = Stream.of(stream);


stream类型转换

转换为数组类型

Stream<String> stringStream = Stream.of("dfsa", "bd", "dc");
String[] strings = stringStream.toArray(length -> new String[length]);

方法引用方式转换为数组类型

String[] strings1 = stringStream.toArray(String[]::new);

转换为list结合

List<String> collect = stringStream.collect(Collectors.toList());

转换为指定类型

Set<String> collect1 = stringStream.collect(Collectors.toCollection(TreeSet::new));

内在和外在

stream的操作相当于是内在操作,上一个博文里面说参数传递的是行为,所以流里面存储的是操作, 下面的lamda如果使用for则是外部操作,因为他存储的是数据,然后取出数据,再操作数据,所以步骤会很复杂.

List<String> list = Arrays.asList("hell", "worl");
list.stream().mapToInt(item->item.length()).filter(Length->Length==5).findFirst().ifPresent(System.out::print);

但是要说明的是stream流他操作串行操作(stream也就是并行实现parallelstream),所以执行的时候一会发现有的时候我们需要把stream流进行合并操作会很麻烦,下面的
flatMap起到了很大作用

 list.stream().mapToInt(item->{
           int length=item.length();
           System.out.println(item);
           return length;
       }).filter(Length->Length==5).findFirst().ifPresent(System.out::print);

使用flatMap 出现的效果,从string[ ] 转换为 string

List<String> collect1 = list.stream().map(item -> item.split(" ")).flatMap(Arrays::stream).distinct().collect(Collectors.toList());

如何快速使用lamda
很简单, 你就把他看成sql语句就行, 把简单的api使用上就可以了,其实我蛮想懂得底层是如何实现的,但是每次看的时候头大都大了,还是慢慢来, 一点点成长~

sql 
select name from student where age > 20 and name ='beijing' order by age desc;

Student student=new Student(25,"judy");
        List<Student> list = new ArrayList<>();
        list.add(student);
        list.stream().filter(student1 -> student1.getAge() > 20).filter(student1 -> student1.getName().equals("judy")).sorted().forEach(student1 -> System.out.println(student.getName()));

group by
Map<Integer, Long> collect = list1.stream().collect(Collectors.groupingBy(Student::getAge, Collectors.counting()));

分区
Map<Boolean, List<Student>> collect1 = list1.stream().collect(Collectors.partitioningBy(student4 -> student.getAge() > 20));
System.out.println(collect1.get(true));

方法引用

方法引用有三种情景下可以使用
类名:: 静态方法名
引用名(对象)::方法名
类名:: 实例名

当看当这三种场景的时候你有没有相关为什么这三种就可以实现? 他们肯定有相似之处,所以可以这样使用,如果你知道,来来来一起交流交流,哈哈哈哈

        //类名::静态方法名
        qtudentList.sort(Qtudent::compareAge);
        qtudentList.forEach(student -> System.out.println(student.getAge()));

        //引用名(对象)::方法名
        QtudentCompare qtudentCompare = new QtudentCompare();
        qtudentList.sort(qtudentCompare::compareAge);
        qtudentList.sort(qtudentCompare::compareName);

        //类名 :: 实例名
        qtudentList.sort(Qtudent::compareAge1);

结尾

lamda我还有一篇就总结完了, 有很多内容我都没有写下来, 因为不知道该怎么写,或者说理解还很浅显, 下面我的计划是springmvc,之后的公众号会在每天进行更新,更新内容, 1 日常自律 2 springmvc源码学习 3 读书 , 准备打卡一周,目标先小点,哈哈哈哈

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章