Search code examples
javaarraysarraylistnested-loops

Nested ArrayList lookup


So I need to return the the departure point for a certain itinerary, here are few examples:

Trips := [ [A,B], [B,C], [C,D] ] The trip in this example started at "A".

Trips := [ [D,E], [F,D], [E,X] ] The trip in this example started at "F".

For this I did 2 loops to compare A to C and D, if A doesn't exist nowhere then it is the departure point.

Is it possible to do it this way (keep the 2 loops) and change something in the condition to get the departure city only?

ArrayList<ArrayList> tripsList = new ArrayList<ArrayList>();
ArrayList<String> trip1 = new ArrayList<String>();
ArrayList<String> trip2 = new ArrayList<String>();
ArrayList<String> trip3 = new ArrayList<String>();

tripsList.add(trip1);
tripsList.add(trip2);
tripsList.add(trip3);

trip1.add("Hamburg");
trip1.add("Berlin");

trip2.add("Mainz");
trip2.add("Frankfurt");    

trip3.add("Frankfurt");
trip3.add("Hamburg");

System.out.println(tripsList);

for (int i=0; i < 3 ; i++)
{
  for (int j=0; j < 3 ; j++)
  {
    if (tripsList.get(i).get(0)!=tripsList.get(j).get(1)) 

      System.out.println("your place is "+tripsList.get(i).get(0));
  } 
}`

Output is the following:

[[Hamburg, Berlin], [Mainz, Frankfurt], [Frankfurt, Hamburg]] your place is Hamburg your place is Hamburg your place is Mainz your place is Mainz your place is Mainz your place is Frankfurt your place is Frankfurt


Solution

  • Use a flag to wait until you check all results:

    Boolean anyMatches = False;
    For (int i= 0; i < 3 ; i++) 
    {
        anyMatches = false;
        For (int j= 0; j < 3 ; j++) 
        {
            If (tripsList.get(i).get(0) == tripsList.get(j).get(1))
            {
                anyMatches = true;
            }
        }
        If (anyMatches == False)  
        {
            SystemThen.out.println("Your Departure City is "+tripsList.Get(i).Get(0));
        }
    }