针对具有不同对象的循环Java优化

时间:2018-07-09 15:12:19

标签: java loops

我想合并到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));
                }
            }

仅一个(用于循环)。

1 个答案:

答案 0 :(得分:0)

您可以做的是使用方法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));
  }
}