How should I instantiate List<List<String>> in Java

Viewed 500

I have the following code:

            List<List<String>> allData= getData()
            
            if (allData== null)
                allData= new ArrayList<ArrayList<String>>();
            // populate allData below

Now I want to initialize allData but I get Type mismatch: cannot convert from ArrayList<ArrayList<String>> to List<List<String>>. What is the correct way I can initialize this?

It is not possible to return ArrayList<ArrayList<String>> from getData()

Thanks!

3 Answers

You do it very simply:

allData = new ArrayList<>();

Then you can add new lists to allData:

List innerList = new ArrayList<>();
innerList.add("some string");
// .... etc ...
allData.add(innerList);

You cannot redefine the generic type of the reference when you instantiate the concrete implementation. The reference is List<List<String>> so the assigned List must be capable of accepting any List<String> as an element. When you instantiated your instance, you attempted to limit this to ArrayList<String>.

The explicit solution is:

allData = new ArrayList<List<String>>();

or more simply as:

allData = new ArrayList<>();
A simple example of getData might be as below -
        
   public static List<List<String>> getData(String fileName){
        List<List<String>> content = null;
        try (Stream<String> lines = Files.lines(Paths.get(fileName ))) {
            content = lines
                    .map(l -> l.split(" "))
                    .map(Arrays::asList)
                    .collect(Collectors.toList());
    
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
Related