-1

I have two lists like this:

List<Post> posts = Post.findAll();
List<Comment> comments = Comment.findAll();

I want to combine these two into one list but with two maps so that when this back to client, it would be one array with two objects with names.

For example output on clientside:

Array:[posts:{...}, comments:{...}]

How do I achieve this in java?

I tried to add two list to new array but it is not very efficient because I need to loop over complete array on client side:

List<Post> posts = Post.findAll();
List<Comment> comments = Comment.findAll();
List listFinal = new ArrayList();
listFinal.addAll(posts);
listFinal.addAll(comments);
return listFinal;
kittu
  • 6,662
  • 21
  • 91
  • 185

2 Answers2

1

This is my implementation, i generalized for n lists.

public static Map<String,Object> mixLists(List<?>...lists){
    Map<String,Object> map = new HashMap<String,Object>();

    for (int i = 0;i < lists.length;i++){
        if (!lists[i].isEmpty())
            map.put(lists[i].get(0).getClass().getName(), lists[i]);
    }
    return map;
}

The function returns a map that you can iterate like a List.

Community
  • 1
  • 1
amchacon
  • 1,891
  • 1
  • 18
  • 29
0

This is not the best solution but you can create a new Object that has Post & Comment in it. Then add elements with same username form Post and Comment to it:

class PostData {
    Post post;
    Comment comment;

    @Override
    public String toString() {
        return post.toString() + comment.toString();
    }
}

Then create a list of that object:

List<PostData> postData = new ArrayList<>();
pratikpncl
  • 508
  • 5
  • 10