java8 stream ,filter 等功能代替for循環


直接上代碼,比較實在。

對象A

public Class A{
    private Long id;

    private String userName;
   
    .....
    
     ....省略get和set方法  
}

在List<A>中,查找userName為hanmeimei的對象A。

在java8中,我們可以這么玩

1,查找集合中的第一個對象。

 Optional<A> firstA= AList.stream() .filter(a -> "hanmeimei".equals(a.getUserName())) .findFirst();

關於Optional,java API中給了解釋。

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

所以,我們可以這樣子使用

if (firstA.isPresent()) {
     A a = firstA.get();   //這樣子就取到了這個對象呢。
}
else {
   //沒有查到的邏輯
}

2,如果想返回集合呢。可是使用這個

 List<A> firstA= AList.stream() .filter(a -> "hanmeimei".equals(a.getUserName())) .collect(Collectors.toList());

3,抽取對象中所有的id的集合

List<Long> idList = AList.stream.map(A::getId).collect(Collectors.toList());

  

總之,超級好用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM