doniyor doniyor - 1 year ago 66
Java Question

Java List with two Objects inside: List<Object o, Object p>

Is it possible to do the following?

List<Object o, Object p> listWithTwoObjects;

I want to retrieve data from a database and save it into this list, concretely in this way

Query query = "retrieve all posts and username, which this user posted";
List<Object o, Object p> userAndPost = query.getResultList();

is the username, and
is the post. I can then render this to my template and show each post with its user.

My question is about the List with two Objects inside. Is it possible and if yes, how and where is the documentation for this?

Answer Source

You can define a Pair class as follows:

public class Pair
    String username;
    int post;

    public Pair(String username, int post)
        this.username = username; = post;

and then simply use List<Pair>, for example:

List<Pair> pairs = new ArrayList<Pair>();
pairs.add(new Pair("doniyor", 12345));

// ...

Pair p = pairs.get(0);
System.out.pritnln(p.username); // doniyor
System.out.pritnln(; // 12345