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

直接上代碼,比較實在。java

對象Aspa

public Class A{
    private Long id;

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

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

在java8中,咱們能夠這麼玩對象

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

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

關於Optional,java API中給瞭解釋。get

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.

因此,咱們能夠這樣子使用io

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

2,若是想返回集合呢。但是使用這個java8

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

3,抽取對象中全部的id的集合class

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

  

總之,超級好用stream

相關文章
相關標籤/搜索