murmur3 hash(hash算法)

HashUtil.java
package com.example.test.util;

import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;

public class HashUtil {
    /**
     * google的murmur算法。 hash环:0 ~ 2 * Integer.MAX_VALUE
     * @author wangxiaolei
     * @date 2020/5/22 16:20
     */
    public static long murmur(String str){
        int murmur = Hashing.murmur3_32().hashString(str, Charsets.UTF_8).asInt();
        long result = (long)murmur + (long)Integer.MAX_VALUE;
        return result;
    }
}

测试:

package com.example.test.util;

import org.apache.commons.lang3.RandomStringUtils;

import java.util.ArrayList;
import java.util.List;

public class TestUtil {
    public static void main(String[] args) throws Exception {
        int positiveCount =0;
        int negativeCount =0;
        int time=0;
        while(time++<=100000) {
            String random = RandomStringUtils.random(32);
            long murmur = HashUtil.murmur(random);
            if(murmur%100>=50){
                positiveCount++;
            }else{
                negativeCount++;
            }
        }
        System.out.println("大于50%概率的数:"+positiveCount);
        System.out.println("小于等于50%概率的数:"+negativeCount);
    }
}

结果:

大于50%概率的数:49916
小于等于50%概率的数:50085
大于50%概率的数:50061
小于等于50%概率的数:49940
大于50%概率的数:49753
小于等于50%概率的数:50248
人生如修仙,岂是一日间。何时登临顶,上善若水前。
原文地址:https://www.cnblogs.com/f-society/p/12951355.html