1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.car; 17 18 import java.util.ArrayDeque; 19 import java.util.Iterator; 20 import java.util.function.Predicate; 21 import java.util.stream.Stream; 22 23 /** 24 * This class keeps track of a limited fixed number of sample data points, correctly removing 25 * older samples as new ones are added, and it allows inspecting the samples, as well as 26 * easily answering N out of M questions. 27 */ 28 class SlidingWindow<T> implements Iterable<T> { 29 private final ArrayDeque<T> mElements; 30 private final int mMaxSize; 31 SlidingWindow(int size)32 public SlidingWindow(int size) { 33 mMaxSize = size; 34 mElements = new ArrayDeque<>(mMaxSize); 35 } 36 add(T sample)37 public void add(T sample) { 38 if (mElements.size() == mMaxSize) { 39 mElements.removeFirst(); 40 } 41 mElements.addLast(sample); 42 } 43 addAll(Iterable<T> elements)44 public void addAll(Iterable<T> elements) { 45 elements.forEach(this::add); 46 } 47 48 @Override iterator()49 public Iterator<T> iterator() { 50 return mElements.iterator(); 51 } 52 stream()53 public Stream<T> stream() { 54 return mElements.stream(); 55 } 56 size()57 public int size() { 58 return mElements.size(); 59 } 60 count(Predicate<T> predicate)61 public int count(Predicate<T> predicate) { 62 return (int)stream().filter(predicate).count(); 63 } 64 } 65