java - 使用不同的对象优化循环Java
问题描述
for
我想与这样的不同对象合并到一个循环中:
for (BBPostLikeLogs postDetail : bbPostLikeLogs) {
if (postDetail.getType() == 4) {
NewFaqQuestion questions = newFaqQuestionRepository.findByIdQuestion(postDetail.getId_post());
if (questions == null) continue;
listObjPosts.add(buildObjPostFromQuestions(questions,userAuth));
}else{
BBPost bbPost = bbPostRepository.findById(postDetail.getId_post());
if(bbPost == null) continue;
listObjPosts.add(buildObjPostFromPosts(bbPost,userAuth));
}
}
和
for (PostResult postDetail : postNeo4j) {
if (postDetail.getType() == 4) {
NewFaqQuestion questions = newFaqQuestionRepository.findByIdQuestion(postDetail.get_id());
if (questions == null) continue;
listObjPosts.add(buildObjPostFromQuestions(questions,userAuth));
}else{
BBPost bbPost = bbPostRepository.findById(postDetail.get_id());
if(bbPost == null) continue;
listObjPosts.add(buildObjPostFromPosts(bbPost,userAuth));
}
}
只有一个(for循环)。
解决方案
您可以做的是创建一个带有方法的接口getType()
并getId()
在循环中迭代,例如for (YourInterface detail : bbPostLikeLogs) { // do whatever }
.
public interface YourInterface {
int getId();
int getType();
}
// implement this interface in your classes
public class PostResult implements YourInterface {
// Your class code here
@Override
public int getId() {
return this.get_id();
}
@Override
public int getType() {
return this.getType();
}
}
public class BBPostLikeLogs implements YourInterface {
// Your class code here
@Override
public int getId() {
return this.getId_post();
}
@Override
public int getType() {
return this.getType();
}
}
// and finally the loop
for (YourInterface detail : bbPostLikeLogs) {
if (detail.getType() == 4) {
NewFaqQuestion questions = newFaqQuestionRepository.findByIdQuestion(detail.getId());
if (questions == null) continue;
listObjPosts.add(buildObjPostFromQuestions(questions,userAuth));
} else {
BBPost bbPost = bbPostRepository.findById(detail.getId());
if(bbPost == null) continue;
listObjPosts.add(buildObjPostFromPosts(bbPost,userAuth));
}
}
推荐阅读
- javascript - 我如何将 html 输入数据传递给 javascript
- javascript - 在响应式布局中使用 CSS“宽度:适合内容”的一个很好的替代方案?
- react-native - 如果我需要从 npm 模块手动自定义代码,我应该怎么做
- oracle - 如何获取已删除重复项的数据?
- css - 如何将样式添加到 NetlifyCMS 编辑器预览
- android - Xamarin Forms App 在 android 8.1 及更低版本上崩溃 | JNI 检测到应用程序错误:mid == null
- php - 当用户输入是多个单词时,PHP 不执行 bash 脚本
- r - 如何修复在 r bookdown 中构建书籍的错误
- django - 如何在 127.0.0.1:8000/admin/auth/user 页面上添加或删除属性?
- android - 注释处理器现在必须显式声明。编译类路径的以下依赖项?