How to add elements of list to another list?
I created a similar situation to test what you were saying. Obviously I do not have access to your specific database to query, so I just focused on the point of your question; the List
combination.
List<String> foods = new ArrayList<String>(); //this is analogous with the list returned from your first queryfoods.add("Beef");foods.add("Chicken");System.out.println("foods(query1): "+foods);List<String> fruits = new ArrayList<String>(); //this is analogous with the list returned from your second queryfruits.add("Apple");fruits.add("Peach");fruits.add("Pear");System.out.println("fruits(query2): "+fruits);foods.addAll(fruits); //this combines the two lists (your two queries)System.out.println("foods(after combination of queries): "+foods);
The output was:
foods(query1): [Beef, Chicken]fruits(query2): [Apple, Peach, Pear]foods(after combination of queries): [Beef, Chicken, Apple, Peach, Pear]
My only thought as to why you are not getting that result would be that one of your queries is not returning anything... I would recommend trying to print out each list prior to adding them together as I did above and see if one is empty.
You actually want to create list of lists, i.e.:
List<List<String>> listOfLists = ...;
You cannot store both strings and lists of strings in the same list that is defined this way. If you indeed want to do this you should just define List<Object>
and you will be able to store there elements of any type. However it is highly not recommended. Generics have been introduced to java to prevent such usage at compile time.
So, what you probably really want is to creatate list of list of strings and then perform queries that return lists of strings and add result to the first list:
List<List<String>> list = new LinkedList<List<String>>();list.addAll(em.createNativeQuery(query1).getResultList());list.addAll(em.createNativeQuery(query1).getResultList());
BTW this approach is not recommended too. Typically if you want to create n-dimensional collection where n>1 you probably should create yet another container class that holds collection and other stuff and then create 1-dimensional collection that stores instances of this class.