📜  Java的布隆过滤器示例(1)

📅  最后修改于: 2023-12-03 15:02:05.706000             🧑  作者: Mango

Java的布隆过滤器示例

布隆过滤器(Bloom Filter)是一种基于概率的数据结构,用于判断一个元素是否可能存在于一个集合中。它以很低的错误率判断一个元素是否已经存在,但不能保证判断结果的准确性。

实现布隆过滤器

下面是一个使用java实现布隆过滤器的示例代码:

import java.util.BitSet;

public class BloomFilter {

    private BitSet bitSet;
    private final int size;
    private final int[] seeds;

    public BloomFilter(int size, int[] seeds) {
        this.bitSet = new BitSet(size);
        this.size = size;
        this.seeds = seeds;
    }

    public void add(String value) {
        for (int seed : seeds) {
            int hash = hash(value, seed);
            bitSet.set(hash % size, true);
        }
    }

    public boolean contains(String value) {
        for (int seed : seeds) {
            int hash = hash(value, seed);
            if (!bitSet.get(hash % size)) {
                return false;
            }
        }
        return true;
    }

    private int hash(String value, int seed) {
        int hash = 0;
        for (char c : value.toCharArray()) {
            hash = seed * hash + c;
        }
        return Math.abs(hash);
    }
}
如何使用布隆过滤器
public class BloomFilterExample {

    public static void main(String[] args) {
        int[] seeds = { 3, 5, 7 };
        BloomFilter bloomFilter = new BloomFilter(100, seeds);

        // 添加元素到布隆过滤器
        bloomFilter.add("apple");
        bloomFilter.add("banana");
        bloomFilter.add("orange");

        // 判断元素是否存在
        System.out.println(bloomFilter.contains("apple"));   // 输出: true
        System.out.println(bloomFilter.contains("grape"));   // 输出: false
        System.out.println(bloomFilter.contains("orange"));  // 输出: true
    }
}

以上代码创建了一个布隆过滤器对象,使用了三个种子(3、5和7)。在布隆过滤器中添加了"apple"、"banana"和"orange"等元素,然后通过contains方法判断元素是否存在。

由于布隆过滤器存在一定的错误率,判断结果不一定是准确的。因此,布隆过滤器适用于对准确性要求不高,但对查询性能要求较高的场景,比如缓存穿透的解决、网站黑名单的过滤等。

注意:布隆过滤器的大小和种子个数需要根据具体应用场景进行调整,以达到合理的错误率和性能。