如何在不打印空值的情况下在数组列表中打印字符串值?

时间:2019-07-04 02:25:29

标签: java string arraylist null

cars =new ArrayList<Car>();
cars.add(new Car(2016,"honda","civic"));
cars.add(new Car(2017,"Lamborghini","aventador")); 
cars.add(new Car(2000,null,"caravan"));
cars.add(new Car(2010,"dodge",null));

我该如何打印和跳过空值:

hondacivicLamborghiniaventadorcaravandodge

1 个答案:

答案 0 :(得分:0)

请勿添加 null只需将其替换为 ""

示例:

cars.add(new Car(2000,"","caravan"));
cars.add(new Car(2010,"dodge",""));

代码:

List<Car> cars = new ArrayList<Car>();

cars.add(new Car(2016,"honda","civic"));
cars.add(new Car(2017,"Lamborghini","aventador")); 
cars.add(new Car(2000,"","caravan"));
cars.add(new Car(2010,"dodge",""));

for(Car c : cars) {
 System.out.print(c.getCompanyName() + "" + c.getCarName());
}

或者将代码更新为此,以跳过null值:

for(Car c : cars) {
   String data = ((c.getCompanyName() != null) ? c.getCompanyName(): "") + ((c.getCarName() != null) ? c.getCarName() : ""); 
   System.out.print(data);
}