簡體   English   中英

如何將列表元素添加到另一個列表?

[英]How to add elements of list to another list?

我有兩個sql查詢,返回列表。 我的代碼:

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

我擁有:列出兩個子列表 - 來自query1的子列表和來自query2的子列表。
我需要的:一個包含來自query1和query2的所有元素的列表。
任何的想法?


問題出現在第一個SQL查詢中。 結果是在對象數組中添加,因此addAll方法無法解決我的問題。

addAll()將起作用。 從兩個查詢中獲取數據的代碼是正確的

我創建了一個類似的情況來測試你在說什么。 顯然我無法訪問您的特定數據庫進行查詢,因此我只關注您的問題; List組合。

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);

輸出是:

foods(query1):  [Beef, Chicken]
fruits(query2):  [Apple, Peach, Pear]
foods(after combination of queries):  [Beef, Chicken, Apple, Peach, Pear]

我唯一想到你沒有得到這個結果的原因是你的一個查詢沒有返回任何內容......我建議嘗試打印出每個列表,然后將它們添加到一起,就像我上面所做的那樣,看看是否為空。

您實際上想要創建列表列表,即:

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

您不能將這些字符串和字符串列表存儲在以這種方式定義的同一列表中。 如果你確實想這樣做,你應該只定義List<Object> ,你就可以存儲任何類型的元素。 但是,強烈建議不要這樣做。 已經在java中引入了泛型以防止在編譯時使用這種用法。

因此,您可能真正想要的是創建字符串列表列表,然后執行返回字符串列表的查詢並將結果添加到第一個列表:

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

BTW也不推薦這種方法。 通常,如果要創建n> 1的n維集合,您可能應該創建另一個容納集合和其他東西的容器類,然后創建存儲此類實例的一維集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM