概况

Jaccard index , 又称为Jaccard相似系数(Jaccard similarity coefficient)用于比较有限样本集之间的相似性与差异性。Jaccard系数值越大,样本相似度越高。
Jaccard系数 - 百度百科

公式

杰卡德相似系数 - 图1
其实总结就是一句话:集合的交集与集合的并集的比例.

代码案例

  1. public static float jaccard(String a, String b) {
  2. if (a == null && b == null) {
  3. return 1f;
  4. }
  5. // 都为空相似度为 1
  6. if (a == null || b == null) {
  7. return 0f;
  8. }
  9. Set<Integer> aChar = a.chars().boxed().collect(Collectors.toSet());
  10. Set<Integer> bChar = b.chars().boxed().collect(Collectors.toSet());
  11. // 交集数量
  12. int intersection = SetUtils.intersection(aChar, bChar).size();
  13. if (intersection == 0) {
  14. return 0;
  15. }
  16. // 并集数量
  17. int union = SetUtils.union(aChar, bChar).size();
  18. return ((float) intersection) / (float)union;
  19. }

注:SetUtils为org.apache.commons commons-collections4包里的工具类