如何遍历单个for循环中的排序列表?

时间:2019-01-16 17:43:50

标签: java

我想遍历排序列表。如果列表包含名称A,则给与第一个A。如果列表中不含名称,则给与第一个B。

我使用两个for循环来完成此操作。

for(Product product : productList) 
{
   if(product.getName().equals("A")) 
   {
      add = product.getName() + product.getDob();
    break;
   }
}

if (add == null)
    {
        for(Product product : productList) 
        {
            if(product.getName().equals("B")) 
            {     
              add = product.getName() + product.getDob();
              break;
            }
        }
}

我希望这个解决方案可以在for循环中使用。

3 个答案:

答案 0 :(得分:1)

在同一循环中检查两个条件:

for(Product product : productList) 
{
   if(product.getName().equals("A")) 
   {
      add = product.getName() + product.getDob();
    break;
   }
   else if(product.getName().equals("B")) 
   {
      addB = product.getName() + product.getDob();
   }
}

if(add == null)
{
add = addB
}

答案 1 :(得分:0)

如果找到A,请尽早返回。如果找到B,请将其存储在变量中,以防找不到任何As。

public Product getFirstAorB()
{
    Product firstB = null;
    for(Product product : productList) 
    {
        if ("A".equals(product.getName())) {
            return product;
        }
        else if (firstB == null && "B".equals(product.getName())) {
            firstB = product;
        }
    }
    return firstB;
}

答案 2 :(得分:0)

尝试使用其他arrya来指示您要寻找的内容。例如:

String [] cr = {"C", "A", "B"};
for(Product product : productList){
    for (String pr : cr)
        if(product.getName().equals(pr)){
            add = product.getName() + product.getDob();
       }
    }

在这种情况下,您只需要一个循环即可检查您的productList。

相关问题