2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.sagercaster.internal.handler;
15 import java.util.Optional;
16 import java.util.SortedMap;
17 import java.util.TreeMap;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
22 * The {@link ExpiringMap} is responsible for storing a list of values of class T
23 * Values older than eldestAge are discarded at each insert of a new one
25 * @author Gaƫl L'hopital - Initial contribution
28 class ExpiringMap<T> {
29 private final SortedMap<Long, T> values = new TreeMap<>();
30 private Optional<T> agedValue = Optional.empty();
31 private long eldestAge = 0;
33 public void setObservationPeriod(long eldestAge) {
34 this.eldestAge = eldestAge;
37 public void put(T newValue) {
38 long now = System.currentTimeMillis();
39 values.put(now, newValue);
40 values.keySet().stream().filter(key -> key < now - eldestAge).findFirst().ifPresent(eldest -> {
41 agedValue = Optional.ofNullable(values.get(eldest));
42 values.entrySet().removeIf(map -> map.getKey() <= eldest);
46 public Optional<T> getAgedValue() {