Search code examples
javaarraylisttraversal

How should i traverse inside two dimensional array list using for each loop


public List<String> findItinerary(List<List<String>> tickets) {
    // creating adjencency list
    
    for(String[] ticket : tickets)
    {
        map.putIfAbsent( ticket[0] ,new PriorityQueue<String>());
        map.get(ticket[0]).add(ticket[1]);
    } 
    dfs("JKF");
    return path;
}

I m trying to create the adjacency list here, but having problem to iterate through list inside the tickets. I was using for each loop , and coming across this error "List cannot be converted to String[] for(String[] ticket : tickets)"


Solution

  • You are using String[] where you should be using List<String>. Change your code to this:

    for(List<String> ticket : tickets)
    {
        map.putIfAbsent(ticket.get(0), new PriorityQueue<String>());
        map.get(ticket.get(0)).add(ticket.get(1));
    } 
    

    Update

    If you want to convert the List<String> in an array use this snippet:

    String[] array = new String[ticket.size()];
    ticket.toArray(array); // fill the array