Problems with hashmap getordefault in java

1

I have a hashmap problem in JAVA.

I'm trying to create a program that reads data from a car, save those cars in an ArrayList, and organize by the manufacturer (that would be the key) the cars of your brand.

public static void main(String[] args) {
    //Value to user answers
    String resp = "s";
    //New list of Car objects
    List<Car> carros = new ArrayList<>();

    try(Scanner input = new Scanner(System.in)){
      while(resp.equalsIgnoreCase("s")){

        //Create a car for every answer
        Car car = new Car();
        String resposta;
        System.out.println("Empresa do carro: ");
        resposta = input.next();
        car.setManufacturerCar(resposta);
        System.out.println("Modelo do carro: ");
        resposta = input.next();
        car.setModelCar(resposta);
        System.out.println("Quantas portas há no carro?");
        resposta = input.next();
        car.setDoorsCar(resposta);
        System.out.println("Marcha manual ou automatica?");
        resposta = input.next();
        car.setGearshift(resposta);

        //Add a car to arraylist
        carros.add(car);

        System.out.println("Deseja continuar?");
        resp = input.next();
      }
    }

    //Map that will be organized
    Map<String, List<Car>> mapCarros = new HashMap<>();

    for(Car c : carros){

      mapCarros.put(c.getManufacturerCar(), carros);

    }

    System.out.println(mapCarros);

}

When I tried to run, saving 2 fuses and a focus, it saves all cars in all manufacturers:

{VW=[Car{manufacturerCar=VW, modelCar=FUSCA, doorsCar=2, gearshift=MANUAL}, Car{manufacturerCar=VW, modelCar=FUSCA, doorsCar=2, gearshift=MANUAL}, Car{manufacturerCar=FORD, modelCar=FOCUS, doorsCar=4, gearshift=AUTOMATICO}], FORD=[Car{manufacturerCar=VW, modelCar=FUSCA, doorsCar=2, gearshift=MANUAL}, Car{manufacturerCar=VW, modelCar=FUSCA, doorsCar=2, gearshift=MANUAL}, Car{manufacturerCar=FORD, modelCar=FOCUS, doorsCar=4, gearshift=AUTOMATICO}]}
    
asked by anonymous 27.09.2017 / 22:17

1 answer

2

You are saving the carros list to all brands. Instead create one for each:

for (Car c : carros){
  List<Car> lista;
  if (mapCarros.containsKey(c.getManufacturerCar())) {
    lista = mapCarros.get(c.getManufacturerCar());
  } else {
    lista = new ArrayList<>();
    mapCarros.put(c.getManufacturerCar(), lista);
  }

  lista.add(c);
}
    
27.09.2017 / 22:55