【问题标题】:Guava Maps.difference with wildcardGuava Maps.difference 与通配符
【发布时间】:2021-10-08 10:22:15
【问题描述】:

我想在 java 11 中使用 Guava 的 Maps.difference 来验证我映射到 Map 中的 Json 字符串中的数据。

通话后的内容(每次使用不同的 uid):

{"uid":"31a340bc-e5ed-440c-8726-34c54dea902a","name":"Jean"}

我想使用这样的模式验证 uid 是否正确生成并且名称是“Jean”:

{"uid":"*","name":"Jean"}

当然Maps.difference 会返回不同的 uid 值...

是否可以在我的验证模式中指定通配符,以便Maps.difference 不返回任何差异?

提前致谢。

【问题讨论】:

  • 这是番石榴Maps.difference吗?
  • 为什么不直接调用 Maps.difference,然后在结果上调用 remove("uid")?
  • @AndyTurner 是的。

标签: java guava


【解决方案1】:

假设您的意思是 Guava 的 Maps.difference:是的,使用 difference(left, right, valueEquivalence) overload

Maps.difference(left, right, new Equivalence<String>() {
  @Override public boolean doEquivalent(String a, String b) {
    return "*".equals(a) || "*".equals(b) || Objects.equals(a, b);
  }

  // You have to hash all strings to the same thing because you
  // don't know if the current item is a "*", or its corresponding
  // item is a "*". But actually it doesn't matter, because I don't
  // think it's invoked in difference.
  @Override public int doHash(String s) { return 0; }
});

【讨论】:

  • 成功了,非常感谢!祝你有美好的一天:)
  • @R.Del,如果它解决了你的问题,请接受这个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 2011-09-09
  • 2012-10-03
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
  • 2014-08-23
相关资源
最近更新 更多