I have parsed through a CSV file and stored it as an array of strings. I'd like to add an item to each sub-array if certain conditions have been met, as shown below. However, I am not able to use the .add()
method and get a "Cannot resolve method" message in my IDE. To try to get around this, I attempted to create a new arraylist in which I placed the contents of the string array, but the problem persisted. How do I make it so that I can add an item to each sublist?
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");
}
}
}
You can't add element in string array directly. You can follow those steps
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
}
}
Or create a List<List<String>>
from List<String[]>
first then add in inner list
Collected from the Internet
Please contact javaer1[email protected] to delete if infringement.
Comments