Skip to content

Instantly share code, notes, and snippets.

@wangshuai1992
Last active November 12, 2020 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wangshuai1992/a40cbefeab21c6d3d11c3f39fb1e419a to your computer and use it in GitHub Desktop.
Save wangshuai1992/a40cbefeab21c6d3d11c3f39fb1e419a to your computer and use it in GitHub Desktop.
CommonUtil.java
public class CommonUtil {
public static String limitedString(String str, int lengthLimit) {
if (StringUtils.isEmpty(str)) {
return str;
}
if (str.length() > lengthLimit) {
str = str.substring(0, lengthLimit) + "...(data too long)";
}
return str;
}
/**
* 根据权重随机选择 map的value为权重值
*
* @param map
* @param <T>
* @return
*/
private static <T> T selectKeyByWeight(Map<T, Integer> map) {
TreeMap<Double, T> weightMap = new TreeMap<>();
// 先排除权重为0的项
map.entrySet().removeIf(entry -> entry.getValue() == 0);
for (Map.Entry<T, Integer> entry : map.entrySet()) {
// 统一转为double
double lastWeight = weightMap.size() == 0 ? 0 : weightMap.lastKey();
// 权重累加
weightMap.put(entry.getValue().doubleValue() + lastWeight, entry.getKey());
}
double randomWeight = weightMap.lastKey() * Math.random();
SortedMap<Double, T> tailMap = weightMap.tailMap(randomWeight, false);
return weightMap.get(tailMap.firstKey());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment