在一个list是一个user对象,现在要从中拿到一个值name等于多少李佳的那条数据,再取出李佳那条数据中数学分数,怎么用流实现,java
时间: 2025-01-19 13:04:19 浏览: 30
要在一个包含User对象的列表中查找名字为“李佳”的用户,并获取该用户的数学分数,可以使用Java的流(Stream)来实现。以下是一个示例代码:
```java
import java.util.List;
import java.util.Optional;
class User {
private String name;
private int mathScore;
public User(String name, int mathScore) {
this.name = name;
this.mathScore = mathScore;
}
public String getName() {
return name;
}
public int getMathScore() {
return mathScore;
}
}
public class Main {
public static void main(String[] args) {
List<User> userList = List.of(
new User("李佳", 90),
new User("张三", 85),
new User("李佳", 95)
);
Optional<User> userOptional = userList.stream()
.filter(user -> "李佳".equals(user.getName()))
.findFirst();
userOptional.ifPresent(user -> System.out.println("李佳的数学分数是: " + user.getMathScore()));
}
}
```
在这个示例中,我们首先创建了一个包含User对象的列表`userList`。然后,我们使用流(Stream)来过滤出名字为“李佳”的用户,并使用`findFirst`方法找到第一个匹配的用户。最后,我们打印出该用户的数学分数。
阅读全文
相关推荐











