JAVA:求字符串相似度

发布于 2021-07-27  1025 次阅读


最近有个项目刚好需要计算字符串相似度,觉得还有点意思,记录一下

public static float jaccard(String a, String b) {
        if (a == null && b == null) {
            return 1f;
        }
        // 都为空相似度为 1
        if (a == null || b == null) {
            return 0f;
        }
        //核心在这个地方:chars()方法是java8中的方法,返回代表字符代码的 int s ( IntStream ) 流
        // boxed()    IntStream类的boxed()方法返回一个由该流元素组成的Stream,每个元素都装箱为一个Integer。
        // collect()收集器,用于把前面的boxed()方法返回的流收集成collect()方法中的参数,这里是集合中的set集合
        Set<Integer> aChar = a.chars().boxed().collect(Collectors.toSet());
        Set<Integer> bChar = b.chars().boxed().collect(Collectors.toSet());
        // 交集数量  
SetUtils.intersection()方法求两个set的交集
        int intersection = SetUtils.intersection(aChar, bChar).size();
        if (intersection == 0) return 0;
        // 并集数量
 SetUtils.union()方法求两个set的并集
        int union = SetUtils.union(aChar, bChar).size();
        //计算交集在并集中的比例,得到字符串相似度
        return ((float) intersection) / (float)union;
    }

欢迎欢迎~热烈欢迎~