嵌套的 ArrayList 查找

Nested ArrayList lookup

所以我需要return某个行程的出发点,这里有几个例子:

行程 := [ [A,B], [B,C], [C,D] ] 本例中的行程开始于 "A".

行程 := [ [D,E], [F,D], [E,X] ] 本例中的行程开始于 "F".

为此我做了2个循环来比较A与C和D,如果A不存在那么它就是出发点。

是否可以这样做(保留2个循环)并更改条件中的某些内容以仅获取出发城市?

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));
  } 
}`

输出如下:

[[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

使用标记等待检查所有结果:

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));
    }
}

找到出发点后停止搜索,希望对您有所帮助

ArrayList<ArrayList<String>> tripsList = new 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("D");
trip1.add("E");

trip2.add("F");
trip2.add("D");

trip3.add("E");
trip3.add("X");

System.out.println(tripsList);

String departure = "";
for (int i = 0; i < tripsList.size(); i++) {
    if (!departure.equals("")) {
        break;
    }
    departure = tripsList.get(i).get(0);
    for (int j = 0; j < tripsList.size(); j++) {
        if ( j == i) {
            continue;
        }
        if (departure.equals(tripsList.get(j).get(1))) {
            departure = "";
            break;
         }
    }
}
System.out.println(departure);