代碼實現 package com.f.fmodules.fuser.bloom;
import com.google.common.base.Charsets;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import java.util.*;
public class BloomFilterDemo {
public static void main(String[] args) {
final int count = 500000;
List<String> stringList = new ArrayList<>(count);
Set<String> stringSet = new HashSet<>();
//建立布隆過濾器 初始化過濾器數據
BloomFilter<String> bloomString = BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8),count);
for (int i =0;i< count;i++){
String id = UUID.randomUUID().toString();
stringList.add(id);
stringSet.add(id);
bloomString.put(id);
}
int wrong = 0;
int right = 0;
for (int i =0;i< count; i++) {
String checkString = i % 100 == 0 ? stringList.get(i) : UUID.randomUUID().toString();
//布隆過濾器 進過hash算法和byte數組 校驗是否存在於集合中
if (bloomString.mightContain(checkString)){
//校驗是否誤判
if (stringSet.contains(checkString)){
right++;
}else{
wrong++;
}
}
}
System.out.println("50萬測試數據-->共抵擋: "+(count - wrong - right)+"次非法入侵"+" 誤判"+wrong);
}
}