我需要創建一個可以為一個鍵存盤多個值的哈希映射,我知道多重映射可以做到這一點,但我還需要將這些值串列保持為特定長度。我需要每個鍵來存盤 n 值的串列,其中那些是最新的 n 值,即如果我達到長度 n 并且我添加另一個值,則添加的第一個值將洗掉值串列并保持目標長度。
我從下面的代碼開始并想要更改它,以便我可以存盤/添加到特定鍵的串列中。
public static void main(final String args[]) throws Exception {
final int maxSize = 4;
final LinkedHashMap<String, String> cache = new LinkedHashMap<String, String>() {
@Override
protected boolean removeEldestEntry(final Map.Entry eldest) {
return size() > maxSize;
}
};
cache.put("A", "A");
System.out.println(cache);
cache.put("B", "A");
System.out.println(cache);
cache.put("C", "A");
System.out.println(cache);
cache.put("D", "A");
System.out.println(cache);
cache.put("E", "A");
System.out.println(cache);
cache.put("F", "A");
System.out.println(cache);
cache.put("G", "A");
}
Output:
{A=A}
{A=A, B=A}
{A=A, B=A, C=A}
{A=A, B=A, C=A, D=A}
{B=A, C=A, D=A, E=A}
{C=A, D=A, E=A, F=A}
I tried changing it to sth like this but can't get it working (python guy here who is getting started with java)
public LinkedHashMap filteroutliers(final String arg, final long arg2) throws Exception{
final int bufferSize = 5;
final LinkedHashMap<Integer, ArrayList<Double>> bufferList = new LinkedHashMap<Integer, ArrayList<Double>>(){
@Override
protected boolean removeEldestEntry(final Map.Entry eldest){
return size() < bufferSize;
}
};
return bufferList;
}
uj5u.com熱心網友回復:
您可以擴展 HashMap 并擁有類似這樣的自定義映射,在這里我維護了一個queue來存盤鍵,因此當達到限制時,您可以洗掉最早的鍵值對 (FIFO)
class CacheMap<K, V> extends HashMap<K, V> {
private static final long serialVersionUID = 1L;
private int MAX_SIZE;
private Queue<K> queue = new LinkedList<>();
public CacheMap(int capacity) {
super();
MAX_SIZE = capacity;
}
@Override
public V put(K key, V value) {
if (super.size() < MAX_SIZE) {
queue.add(key);
} else {
super.remove(queue.poll());
}
super.put(key, value);
return value;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/435068.html
上一篇:布林值的Java流映射?
