Search code examples
javahashmapjava-streamiterationcucumber-java

Find a value by the key in a List of Maps


I have a list of maps List<Map<String,String>> input.

Which can be represented in the following manner:

[{AddressField=AddressUsageType, AddressValue=PRINCIPAL},
 {AddressField=StreetNumber, AddressValue=2020},
 {AddressField=StreetName, AddressValue=Some street}]

I would like to get the AddressValue for a particular AddressField.

For example, I want to get the value "PRINCIPAL" for the key "AddressUsageType".

I have tried using filters and many other MAP functions, but couldn't end up with a proper solution.

This is my code snippet that gets the value of 1st key-value pair:

DataTable table;
List<Map<String,String>> input= table.asMaps(String.class, String.class);

    String AddressField = input.get(0).get("AddressField");
    String AddressValue = input.get(0).get("AddressValue");
    System.out.println("AddressField " +AddressField);
    System.out.println("AddressValue " +AddressValue);

Here is the output of the above snippet:

AddressField AddressUsageType
AddressValue PRINCIPAL

Solution

  • I think this is what you're looking for:

    Map<String, String> map = data.stream()
            .filter(m -> m.values().contains("AddressUsageType"))
            .findFirst()
            .orElse(null);
    
    if (map != null) {
        System.out.println("AddressField " + map.get("AddressField"));
        System.out.println("AddressValue " + map.get("AddressValue"));
    }
    

    Here's also a test main

    public class Test {
        public static void main(String[] args) {
            List<Map<String, String>> data = new ArrayList<>();
    
            Map<String, String> map1 = new HashMap<>();
            map1.put("AddressField", "AddressUsageType");
            map1.put("AddressValue", "PRINCIPAL");
            data.add(map1);
    
            Map<String, String> map2 = new HashMap<>();
            map2.put("AddressField", "StreetNumber");
            map2.put("AddressValue", "2020");
            data.add(map2);
    
            Map<String, String> map3 = new HashMap<>();
            map3.put("AddressField", "StreetName");
            map3.put("AddressValue", "Some street");
            data.add(map3);
    
            Map<String, String> map = data.stream()
                    .filter(m -> m.values().contains("AddressUsageType"))
                    .findFirst()
                    .orElse(null);
    
            if (map != null) {
                System.out.println("AddressField " + map.get("AddressField"));
                System.out.println("AddressValue " + map.get("AddressValue"));
            }
        }
    }
    

    Output

    enter image description here