Conversion of Cucumber DataTable to Map

Neha picture Neha · Jun 18, 2018 · Viewed 13k times · Source

I am using Cucumber Data Tables. I want to convert this Data Table into a Map rather than a list. So basically what if I use the Header Row as Key and the data rows as value for the key. How should I do that?

Let me share 1 example to be more clear.

Given the following animals:

  | Type  | BabyAnimal |    
  | cow   | Calf       |
  | horse | Pony       |
  | sheep | Lamb       |

Instead of creating a List<List<String>> here, it is a better approach to use a List<Map<String,String>> here. Map's Key should contain 'Type' and 'BabyAnimal' and values should contain the respective values. So the Map entities would be:

<Type,cow>,<BabyAnimal,Calf>
<Type,horse>,<BabyAnimal,Pony>
<Type,sheep>,<BabyAnimal,Lamb>

How would we do that? I feel this is a better approach of doing because we are fetching the data from the keys. eg List(1).Map.get(Type) Whereas in case of List we would have to do a get(0), get(1) and there are chances of using incorrect data.

Answer

M.P. Korstanje picture M.P. Korstanje · Jun 22, 2018

And adding a second answer because the generic types in your question got munched by the html.

Given the following animals:

| Type  | BabyAnimal |    
| cow   | Calf       |
| horse | Pony       |
| sheep | Lamb       |

And assuming you want this to be your step definition:

@Given("all baby animal details")
public void allMapDetails(List<Map<String, String>> animals) {
    System.out.println(animals);
}

Then the table will be automatically converted to a list of maps of string to string.