Find values in a map that ARE NOT in a list of pojos

ssdev :

In my REST api, I'm accepting a map that looks like this -

Map<String, Object> newSettings-

{
  "showGrantsInGrid": false,
  "isPrimeUser": true,
  "hasRegistered": true
}

I need to compare those settings to an existing list of settings. That List looks like this -

List<Setting> currentSettings -

[
  {
    "settingName": "showGrantsInGrid",
    "settingValue": "false",
  },
  {
    "settingName": "isPrimeUser",
    "settingValue": "true",
  }
]

This is what a Setting object looks like -

public class Setting {
    private String settingName;

    private String settingValue;

    // getters and setters ...

I'm trying to figure out how to find the entries that are in the map that was sent to the REST api that ARE NOT in the List of Settings. In the above example, that should be "hasRegistered".

Everything I've tried so far hasn't worked. Anyone have any ideas?

Hadi J :

You can do like this:

Set<String> settingNames = currentSettings.stream()
          .map(Setting::getSettingName)
          .collect(Collectors.toSet());

then

newSettings.keySet().stream()
           .filter(key->!settingNames.contains(key))
           .collect(Collectors.toList());

By one step:

currentSettings.stream()
            .collect(Collectors
                    .collectingAndThen(Collectors
                                    .mapping(Setting::getSettingName, Collectors.toSet()),
                         settingName -> newSettings.keySet().stream()
                              .filter(key -> !settingName.contains(key))
                              .collect(Collectors.toList())
                    )
            );

Note: I'm not sure about its performance compared with the previous one.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360779&siteId=1