Reputation: 1232
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.
Upvotes: 0
Views: 2017
Reputation: 21
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
Upvotes: 0
Reputation: 14363
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());
}
Upvotes: 0
Reputation: 31
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());
}
Upvotes: 0
Reputation: 2653
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");
Upvotes: 1
Reputation: 7326
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).
Upvotes: 1