[英]How to combine arrays into one array in while loop in Java
我有一個來自csv文件的字符串流。 這些字符串將轉換為數組,並且必須作為值放置在Object的setter中,並將Object放入hashMap中。 我如何將所有連接數組合並為一個,然后才使用Set方法? 有沒有比set方法前並置數組更好的解決方案?
這是我的代碼:
HashMap<Integer, Publication> innerMap = new HashMap<>();
try {
CsvReader csv = new CsvReader(filename);
csv.readHeaders();
while (csv.readRecord()) {
int id = Integer.parseInt(csv.get("ID"));
Publication pub = new Publication();
String names = csv.get("Names");
String[] namesArr = names.split(",");
if (!innerMap.containsKey(id)) {
innerMap.put(id, new Publication());
}
String[] merged = ????
pub.setNames(merged);
innerMap.put(au.getIdx(), pub);
}
csv.close();
} catch (IOException e) {
System.out.println("Exception : " + e);
}
首先將它們存儲在List
:
List<String[]> list = new ArrayList<>;
...
list.add(namesArr);
然后,一旦您完成閱讀:
int size = 0;
for (String[] arr : list) {
size += arr.length;
}
List<String> all = new ArrayList<>(size);
for (String[] arr : list) {
all.addAll(Arrays.asList(arr));
}
第一個循環有助於分配必要的內存來保存所有數據(否則,在第二個循環中向其添加元素時,內部可能會在ArrayList
內部進行大量重新分配和數組復制)。
這已經使用Apache Commons得到了解答- 如何在Java中連接兩個數組?
這是純Java 8方式
String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "e", "f", "g" };
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
String[] arr = Stream.concat(stream1, stream2).toArray(String[]::new);
看起來如果映射鍵存在,則您要提取值,附加其他值,然后再放回去。
我將使用一個吸氣劑,然后運行此concat函數,該函數返回一個新數組。 由於數組受其大小限制,因此除非增加一個新的數組並復制所有內容,否則無法增長。
連接2個字符串數組,其中A優先出現:
String[] concat( String[] a, String[] b){
String[] out = new String[a.length + b.length]();
int i = 0;
for (int j = 0; j < a.length; j++){
out[i] = a[j]
i++;
}
for (int j = 0; j < b.length; j++){
out[i] = b[j];
i++;
}
return out;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.