javahashmapjava-stream

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

  • Since in your code you have a List where each element is a Map with a single mapping, you could stream the list and filter for the first map containing the value AddressUsageType.

    Your code could be written like this:

    Map<String, String> map = myList.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 is also a test main at OneCompiler.