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