嵌套ArrayList查找

时间:2019-01-21 23:06:48

标签: java arrays arraylist nested-loops

因此,我需要返回某个行程的出发点,以下是一些示例:

Trips:= [[[A,B],[B,C],[C,D]] 在此示例中,行程从“ A”开始。

Trips:= [[[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

2 个答案:

答案 0 :(得分:0)

使用标志来等待,直到您检查所有结果:

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

答案 1 :(得分: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);