简体   繁体   中英

How to iterate HashMap<String, ArrayList<Car>>

How to print ArrayList from HashMap?

Map<String, ArrayList<Car>> cars = new HashMap<String, ArrayList<Car>>;

ArrayList<Car> carList = cars.get("bmw");

    for (int i = 0; i < carList.size(); i++) {
        System.out.println(carList.get(i));
    }

The code causes:

java.lang.NullPointerException

Despite the "bmw" key exists and is populated.

Try adding in a

System.out.println(cars.get("bmw"));

to check and see what exactly is in it (in the Map, and the ArrayList of cars).

Iterator<String> itr = carList.iterator();
    while (itr.hasNext()) {
      String element = itr.next();
      System.out.print(element + " ");
    }

Inoder to do this carList should not be a null value.
To add values to ArrayList you can use

carList.add("Some value");

The easiest way to iterate through your list is to use foreach:

ArrayList<Car> carList = cars.get("bmw");  
for (Car car : carList) {
    System.out.println(car.getYourValueToPrint());
}

The safest way to iterate over ArrayList will be via enhanced for each loop which saves you the pain of a NullPointerException :

ArrayList<Car> carList = cars.get("bmw");
for(Car car: carList){
    car.doAnyOpertation();
    System.out.println(car.getAnyValue());
}
ArrayList<Car> carList = cars.get("bmw");
for(Car car: carList){
    car.doAnyOpertation();
    System.out.println(car.getAnyValue());
}

Even in this if carList is null, then line
for(Car car: carList) with throw NPE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM