简体   繁体   中英

hashmap, java8, null/empty check

I have a map as follows:

private Map<String, Object> map = new HashMap<>();

This map contains its key value pair as:

Key Value

myKey -> value

value -> Another value

As shown above, this map would either be empty, or have key value pairs including above key values ( myKey , value and value as key to next element).

I want to check if this map:

is empty or not

has myKey and value and if yes, has Another value . My code has so many if else so wanted to avoid with better way to find Another value

  if (map.isEmpty()) {
        if (map.get(myKey) != null || StringUtils.isNotBlank(map).get(myKey).toString())) {
            String nextKey = map.get(myKey).toString();
            if (StringUtils.isNotBlank(nextKey) && map.get(nextKey) != null
                    && StringUtils.isNotBlank(map.get(nextKey).toString())) {
                String finalValue = map.get(nextKey).toString();
            }
        }

    } else {
        flag = true; 
    }

You can use Map's containsKey method to avoid multiple if

Map<String,String> map = new HashMap<>();
    if(map.containsKey(myKey) && StringUtils.isNotBlank(map.get(myKey)) 
                             && map.containsKey(map.get(myKey))) {
        flag=false;
    } else {
        flag=true
    }

A more simplified version of above code would be

flag = StringUtils.isBlank(map.get(myKey)) || !map.containsKey(map.get(myKey));

I guess what your looking for is an ordered list of objects. Why not just keep a list?

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