How to keep the last 100 objects inserted in an ArrayList? This will be constantly fed but I want to keep only the last 100.
How to keep the last 100 objects inserted in an ArrayList? This will be constantly fed but I want to keep only the last 100.
The simplest way to solve this problem is to apply the concept of FIFO (First in, first out)
.
Fifo refers to a data structure of the queue type. Lists are widely used in scheduling to implement queues. In a FIFO type queue, the elements are queued and removed (or processed) in order of arrival. The basic idea of the queue is that we can only insert a new element at the end of the queue and we can only remove the element from the beginning.
Youcanseemore here
In addition to this concept you will have to limit the volume of records that you want to store, so I suggest using Apache Commons Collections
If you are using maven you can do the import:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
If you are using gradle
'compile group: 'org.apache.commons', name: 'commons-collections4', version: '4.1''
Basically, you just need to add the commons-collections4
library to your dependencies, for example I used summer 4.1.
After doing the import you can create your previously limited lists for example:
new CircularFifoQueue<String>(100)
new CircularFifoQueue<Integer(100)
among others.
For example, I made an example by creating random strings and storing them in the queue, at the end I display the remaining values:
public static void main(String args[]) {
Collection<String> fifo = new CircularFifoQueue<String>(100);
for (int i = 1; i <= 500; i++) {
String id = UUID.randomUUID().toString();
System.out.println(i + " - " + id);
fifo.add(id);
}
System.out.println("----> Result Fifo <----");
int i = 1;
for (String id : fifo) {
System.out.println(i++ + " - " + id);
}
}
I was able to get what I wanted with while.
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> arr = new ArrayList<>();
for(int i = 0;i < 150 ; i++){
arr.add(Integer.toString(i));
}
while(arr.size() >= 100){
arr.remove(0);
}
for(String x : arr){
System.out.println(x);
}
}