How to add list items to another list?

I have two sql queries that return lists. My code is:

List<String> list = em.createNativeQuery(query1).getResultList(); list.addAll(em.createNativeQuery(query2).getResultList()); 

What I have: A list with two sublists - subscriptions from request1 and subscriptions from request2.
What I need: one list with all the elements from query1 and query2.
Any idea?


The problem was in the first sql query. The result was added to the array of objects, so the addAll method does not solve my problem.

+4
source share
3 answers

addAll () will work. The code is correct for receiving data from the request

+4
source

I created a similar situation to check what you say. Obviously, I don't have access to your specific database for the query, so I just focused on the question of your question; 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 on why you are not getting this result would be that one of your queries returns nothing ... I would recommend trying to print each list before adding them together, as I did above, and see one is empty.

+2
source

Are you sure you want to create a list of lists, i.e.:

List<List<String>> listOfLists = ...;

You cannot save both lines and line lists in the same list that is defined in this way. If you really want to do this, you just need to define a List<Object> , and you can store any type of element there. However, this is highly discouraged. Generics were introduced in java to prevent this use at compile time.

So, you probably really want to create a list of row lists, and then run queries that return lists of rows and add the 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()); 

By the way, this approach is also not recommended. Usually, if you want to create an n-dimensional collection, where n> 1, you probably should create another container class containing the collection and other materials, and then create a one-dimensional collection that stores instances of this class.

0
source

Source: https://habr.com/ru/post/1485803/


All Articles