1

I need to get userId value from the map and that can be present either in user1 key or user2 key or user3 key or user4 key in the map. Only one key will be present in the map at a time, no multiple keys will be present.

So I started off with below code which checks if user1 is present or not and if it is present extract user1 key value otherwise extract user2 key value. So should I keep adding user3 and user4 check as well in it? If yes it will become very long..

Map<String, String> holder = Utils.parseStringToMap(payload);
String userId = holder.containsKey("user1") ? holder.get("user1") : holder.get("user2");

Is there any better way by which I can extract userId value depending on what key is present? I am using Java 7.

Note: here key name in the map for that field can be any name. It won't be userx where x is a number so I cannot use for loop logic here.

john
  • 11,311
  • 40
  • 131
  • 251

3 Answers3

1

You could iterate the keys in a loop:

for (int i = 1; i <= 4; i++) {
    final String key = "user" + i;
    if (holder.containsKey(key)) {
        // ... process the found key and value
        break;
    }
}

This would allow you to easily extend your keyspace in the future by just changing the upper bound (4 in this example).

If your names do not have a common pattern like userX, you could have an explicit list of them:

String[] keys = {"key1", "user2", "somethingelse"};
for (final String key : keys) {
    if (holder.containsKey(key)) {
        // ... process the found key and value
        break;
    }
}
Roman Puchkovskiy
  • 11,415
  • 5
  • 36
  • 72
1

You should introduce a helper method that provides a var-args parameter to transmit any userId String to match.
It would be more readable and flexible.
For example :

public String getUserId(Map<String, String> valueByUserIds, String... userIdsToMatch){
   for (String userIdToMatch : userIdsToMatch){
       if (holder.containsKey(userIdToMatch)){
         // or spare an invocation by using only holder.get(userIdToMatch) if the value should never be null
          return holder.get(userIdToMatch);
       }
   }
   return null; // or throw an exception
}

And you can use it in this way :

Map<String, String> holder = Utils.parseStringToMap(payload);
String userValue = getUserId(holder, "user1");
String userValue = getUserId(holder, "user1", "user2");
String userValue = getUserId(holder, "user1", "user2", "user3");
davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

I'd wrap the possible keys in a list and iterate over them:

private static String getFromFirstKey
    (Map<String, String> map, List<String> keys) {
    for (String key : keys) {
        if (map.containsKey(key)) {
            return map.get(key);
        }
    }
}

public static void main(String[] args) {
    Map<String, String> holder = Utils.parseStringToMap(payload);
    String userId =
      getFromFirstKey(holder, Arrays.asList("user1", "user2", "user3", "user4"));
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350