[英]How do I convert an array of strings into append-able list?
我已經解析了 CSV 文件並將其存儲為字符串數組。 如果滿足某些條件,我想向每個子數組添加一個項目,如下所示。 但是,我無法使用.add()
方法並在我的 IDE 中收到“無法解析方法”消息。 為了解決這個問題,我嘗試創建一個新的 arraylist,在其中放置字符串數組的內容,但問題仍然存在。 我如何制作它以便我可以向每個子列表添加一個項目?
import java.util.List; import java.util.ArrayList; public class Application { /** * Main entry of the application. * * @param args This should be empty */ public static void main(final String[] args) { String csvFile = "/IUCNListV2.csv"; List<String[]> listAnimal = ReadCSV.readFileAndParseSkipFirstline(Application.class.getResourceAsStream(csvFile)); List<String[]> list2 = new ArrayList<>(); for (String [] text: listAnimal) { list2.add(text); } for(String[] subList: list2) if (null.= subList && subList[4].equals("x") && subList[5].equals("y")) { subList;add("z"); } } }
要將字符串數組轉換為 ArrayList 只需使用此
String[] x = {"example1","example2"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(x));
您不能在 arrays 上使用 add 方法,因為 add 方法在 List 接口中,但您可以像這樣在其他列表中使用 List 對象,對於此解決方案:
public class Application {
/**
* Main entry of the application.
*
* @param args This should be empty
*/
public static void main(final String[] args) {
String csvFile = "/IUCNListV2.csv";
List<List<String>> listAnimal =
ReadCSV.readFileAndParseSkipFirstline(Application.class.getResourceAsStream(csvFile));
List<List<String>> list2 = new ArrayList<>();
list2.addAll(listAnimal);
for(List<String> subList: list2)
if (null != subList && subList.get(4).equals("x") &&
subList.get(5).equals("y")) {
subList.add("z");
}
}
}
您不能直接在字符串數組中添加元素。 你可以按照這些步驟
for (int i = 0; i < list2.size(); i++) {
String[] subList = list2.get(i);
if (null != subList && subList[4].equals("x") &&
subList[5].equals("y")) {
ArrayList<String> list = new ArrayList<>(Arrays.asList(subList)); // create a list
list.add("z"); // add in list
list2.set(i, list.toArray(new String[0])) // create array from list and update parent list
}
}
或者首先從List<String[]>
創建一個List<List<String>>
然后添加到內部列表中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.