首先创建一个Student类
@Data
public Class Student{
private Long id;
private String name;
}
在List<Student>中查找name为ZhangSan的对象Strudent
在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.
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());
---------------------
原文:https://blog.youkuaiyun.com/sunayn/article/details/84144767
本文详细介绍了如何使用Java8的Stream API进行集合操作,包括查找特定元素、收集满足条件的对象和抽取对象属性值等常见场景的实现方式。通过具体代码示例,读者可以快速掌握Stream API的使用技巧。
4万+

被折叠的 条评论
为什么被折叠?



