java 如何使用Map.merge来增加计数器的值?

mfpqipee  于 2023-08-01  发布在  Java
关注(0)|答案(2)|浏览(188)

我正试图通过实现Map.merge()来重构一个在HashMap中以更有效的方式计算键的方法。如何在下面的代码中实现:

  1. public Map<Character, Integer> countCharacterUsage(String input) {
  2. Map<Character, Integer> characterToCountUsage = new WeakHashMap<>();
  3. for (char symbol : input.toCharArray()) {
  4. if (characterToCountUsage.containsKey(symbol)) {
  5. int symbolsCount = characterToCountUsage.get(symbol);
  6. characterToCountUsage.put(symbol, ++symbolsCount);
  7. } else {
  8. characterToCountUsage.put(symbol, 1);
  9. }
  10. }
  11. return characterToCountUsage;
  12. }

字符串

kqlmhetl

kqlmhetl1#

你可以使用计算

  1. characterToCountUsage.compute(symbol, (k,v)-> v==null ? 1 : v+1);

字符串
与merge

  1. characterToCountUsage.merge(symbol,1, (k,v)-> v+1);

zzoitvuj

zzoitvuj2#

根据merge()行为:

  1. V oldValue = map.get(key);
  2. V newValue = (oldValue == null) ? value :
  3. remappingFunction.apply(oldValue, value);
  4. if (newValue == null)
  5. map.remove(key);
  6. else
  7. map.put(key, newValue);

字符串
正确的做法是

  1. characterToCountUsage.merge(symbol, 1, (oldValue, value) -> oldValue + 1);


但如果你想压缩它甚至更多,这里是一个班轮:

  1. Map<Character, Integer> characterToCountUsage = input.chars().mapToObj(c -> (char) c).collect(Collectors.toMap(Function.identity(), newKey -> 1, (value1, value2) -> value1 + value2));

展开查看全部

相关问题