对类中的方法进行另一种写法
时间: 2024-03-25 15:39:22 浏览: 10
好的,那我给您提供一种使用流式编程的写法,您可以参考一下:
```
package 大作业.first;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class Post {
private String content;
private LocalDateTime timestamp;
private List<Comment> comments;
public Post(String content) {
this.content = content;
this.timestamp = LocalDateTime.now();
this.comments = new ArrayList<>();
}
public void display() {
System.out.println(content);
System.out.println("Post time: " + timestamp);
System.out.println("Comments display:");
comments.stream().forEach(comment -> comment.display());
}
public void addComment(Comment comment) {
comments.add(comment);
}
// getters and setters
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
}
```
在这个版本的 `display` 方法中,我们使用了 Java 8 引入的流式编程 API,将集合中的每个元素都传递给 `Comment.display()` 方法进行展示。这种写法简洁明了,可以减少繁琐的遍历代码。