Skip to content

Instantly share code, notes, and snippets.

@AlbertProfe
Created September 20, 2024 11:20
Show Gist options
  • Save AlbertProfe/5cb37c23274afac4cc4071bf9cdbddcd to your computer and use it in GitHub Desktop.
Save AlbertProfe/5cb37c23274afac4cc4071bf9cdbddcd to your computer and use it in GitHub Desktop.
How to iterate key-valu of a HashMap
import java.util.HashMap;
import java.util.Map;
public class CarExample {
public static void main(String[] args) {
// Create a HashMap of cars
Map<String, Car> cars = new HashMap<>();
cars.put("ABC123", new Car("Toyota", "Corolla"));
cars.put("XYZ789", new Car("Honda", "Civic"));
cars.put("DEF456", new Car("Ford", "Mustang"));
// Iterate through the HashMap
for (Map.Entry<String, Car> entry : cars.entrySet()) {
String licensePlate = entry.getKey();
Car car = entry.getValue();
System.out.println("License Plate: " + licensePlate + ", Car: " + car);
}
}
}
class Car {
private String import java.util.HashMap;
import java.util.Map;
public class CarExample {
public static void main(String[] args) {
// Create a HashMap of cars
Map<String, Car> cars = new HashMap<>();
cars.put("ABC123", new Car("Toyota", "Corolla"));
cars.put("XYZ789", new Car("Honda", "Civic"));
cars.put("DEF456", new Car("Ford", "Mustang"));
// Iterate through the HashMap
for (Map.Entry<String, Car> entry : cars.entrySet()) {
String licensePlate = entry.getKey();
Car car = entry.getValue();
System.out.println("License Plate: " + licensePlate + ", Car: " + car);
}
}
}
class Car {
private String make;
private String model;
public Car(String make, String model) {
this.make = make;
this.model = model;
}
@Override
public String toString() {
return make + " " + model;
}
}make;
private String model;
public Car(String make, String model) {
this.make = make;
this.model = model;
}
@Override
public String toString() {
return make + " " + model;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment