skip to Main Content

I am trying to create a list that holds up to the latest 10 values, however, these values need to be the latest. For example, I have a loop that outputs 100 numbers but only the lastest 10 numbers should be saved in this list.

Can anyone help me with this scenario as I am stuck and new to JAVA?

2

Answers


  1. Try Guava library it has EvictingQueue

        EvictingQueue<String> queue = EvictingQueue.create(10);
        //code test
         //add 100 strings to queue 
            for(int i =0;i<100;i++){
                        queue.add ("some text " + i);
                    }
      //Iterate through array and print
      for(String x: queue){
                System.out.println (x);
            }
    
    Output: 
    Some Text90
    Some Text91
    Some Text92
    Some Text93
    Some Text94
    Some Text95
    Some Text96
    Some Text97
    Some Text98
    Some Text99
    

    It’s Android compatible, but 'com.google.common.collect.EvictingQueue' is marked unstable with @Beta :

    implementation("com.google.guava:guava:30.1.1-android")
    
    Login or Signup to reply.
  2. You can simply create a List with limitation, by extending an existing List-Implementation and overriding the add-method like this:

    class LimitedList<E> extends LinkedList<E> {
      private final int maxElements;
    
      public LimitedList(int maxElements) {
        this.maxElements = maxElements;
      }
    
      @Override
      public boolean add(E e) {
        if(this.size() > maxElements - 1) {
          this.remove(0);
        }
        return super.add(e);
      }
    }
    

    Note: in ArrayList there are also other methods to add elements, so maybe these also need to be overriden.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search