首页 > 解决方案 > 使用不同的对象优化循环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循环)。

标签: javaloops

解决方案


您可以做的是创建一个带有方法的接口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));
  }
}

推荐阅读