简体   繁体   中英

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

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?

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.

First, you can get all of the keys of newSettings with:

    List<String> newOnes = new ArrayList<>(); 

    Set<String> keys = newSettings.keySet();
    for (String key: keys) {
        // then, search through the list to see if it contains that name
        boolean present = false;
        for (Setting setting : currentSettings) {
             if (setting.getSettingName().equals(key)) {
                 present = true;
                 break;
             }
}
        if (!present) 
            newOnes.add(key);


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM