直接上代碼,比較實在。
對象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());
總之,超級好用
