Taking Key Value pairs from a List<Object> and adding to a new List<Object>

Viewed 490

I have a List<Object> that contains Objects with Key Value pairs. I want to loop through and if a Key value contains a certain Value. I want to pull that object and create a new List<Object> with only those values. How could i do this?

 for (int i = 0; i < dbResults.size(); i++) {
            Map<String, Object> map = (Map<String, Object>) dbResults.get(i);
            for (String key : map.keySet()) {
            System.out.println("Key: " + key + " maps to value: " + map.get(key));
            }
       }

enter image description here

1 Answers

If you are allowed to use streams, you can use the following code snippet:

String valueToSearch = "ronseal";

List<Object> list = dbResults.stream()
                             .filter(i -> (i instanceof Map)) // filter out non-maps (optional step)
                             .map(i -> (Map<String, Object>) i) // convert objects to maps
                             .flatMap(m -> m.values().stream()) // merge values from maps into single stream
                             .filter(e -> e.equals(valueToSearch)) // filter by the given value
                             .collect(Collectors.toList()); // get new list

list.forEach(System.out::println);

//------
// in case you need to get list of maps
List<Map<String, Object>> listMaps = dbResults
    .stream()
    .map(i -> (Map<String, Object>) i)
    .filter(m -> m.containsValue(valueToSearch))
    .collect(Collectors.toList());

listMaps.forEach(System.out::println);

Output:

ronseal

{test=@newbayfox, Tag=ronseal, str_id=14753491397}
Related