Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add AnyMaps#upsert method #4

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/main/java/com/cinchapi/common/collect/AnyMaps.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Ints;

/**
Expand Down Expand Up @@ -67,6 +69,46 @@ public static <T> void rename(String key, String newKey,
}
}

/**
* Put or update the value associated with the {@code path} within a
* possibly nested {@link Map} that contains other maps and collections as values.
*
* @param path a navigable path key (e.g. foo.bar.1.baz)
* @param value
* @param map
* @return
*/
@SuppressWarnings("unchecked")
public static <T> Object upsert(String path, Object value,
Map<String, ? extends Object> map) {
List<String> components = Lists.newArrayList(path.split("\\."));
Map<String, Object> source = (Map<String, Object>) map;
String key;
do {
key = components.remove(0);
//TODO: handle case where the key is a Number
if(!components.isEmpty()) {
try {
Map<String, Object> next = (Map<String, Object>) source
.get(key);
if(next == null) {
next = Maps.newHashMap();
source.put(key, next);
}
source = next;

}
catch (ClassCastException e) {
throw new IllegalArgumentException("Illegal path " + path
+ ". The component mapped from " + key
+ " is not an Map");
}
}
}
while (!components.isEmpty());
return source.put(key, value);
}

/**
* Return a possibly nested value in a {@link Map} that contains other maps
* and collections as values.
Expand Down