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 讀書 , 準備打卡一週,目標先小點,哈哈哈哈

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