• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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.util;
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  * @param <T> data to iterate
29  */
30 public class SlidingWindow<T> implements Iterable<T> {
31     private final ArrayDeque<T> mElements;
32     private final int mMaxSize;
33 
34     /** TODO: add javadoc */
SlidingWindow(int size)35     public SlidingWindow(int size) {
36         mMaxSize = size;
37         mElements = new ArrayDeque<>(mMaxSize);
38     }
39 
40     /** TODO: add javadoc */
add(T sample)41     public void add(T sample) {
42         if (mElements.size() == mMaxSize) {
43             mElements.removeFirst();
44         }
45         mElements.addLast(sample);
46     }
47 
48     /** TODO: add javadoc */
addAll(Iterable<T> elements)49     public void addAll(Iterable<T> elements) {
50         elements.forEach(this::add);
51     }
52 
53     @Override
iterator()54     public Iterator<T> iterator() {
55         return mElements.iterator();
56     }
57 
58     /** TODO: add javadoc */
stream()59     public Stream<T> stream() {
60         return mElements.stream();
61     }
62 
63     /** TODO: add javadoc */
size()64     public int size() {
65         return mElements.size();
66     }
67 
68     /** TODO: add javadoc */
count(Predicate<T> predicate)69     public int count(Predicate<T> predicate) {
70         return (int) stream().filter(predicate).count();
71     }
72 }
73