I have two sql queries, which returning lists. My code:
List<String> list = em.createNativeQuery(query1).getResultList();
list.addAll(em.createNativeQuery(query2).getResultList());
What I have: List with two sublists - sublist from query1 and sublist from query2.
What I need: One list with all elements from query1 and query2.
Any idea?
Problem was in first sql query. Result was adding in object array, therefore addAll method not solves my problem.
Use the extend() Method to Append a List Into Another List in Python. Python has a built-in method for lists named extend() that accepts an iterable as a parameter and adds it into the last position of the current iterable. Using it for lists will append the list parameter after the last element of the main list.
Join / Merge two lists in python using + operator In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.
append() to add a list inside of a list. To add a list inside a list as an element, use the list. append() method. The list append() is a built-in Python function that adds a single element to the existing 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 query
foods.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 query
fruits.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.
addAll() will work. code is correct to get data from both the query
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With