-1

I need a data structure queue, linked list of hash map or stack, to be able to save last 10 objects of user data, and if user try to add item number 11 it should delete item number 0, and make sure the list is only have the last 10 items.

Is there any library or algorithm to achieve that or I have to implement the algorithm by myself?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Amira Elsayed Ismail
  • 9,216
  • 30
  • 92
  • 175

3 Answers3

2

You may use the EvictingQueue from Google Guava library. According to docs:

An evicting queue must be configured with a maximum size. Each time an element is added to a full queue, the queue automatically removes its head element.

Hamid Fadishei
  • 830
  • 2
  • 10
  • 16
2

You can create your own caching mechanism quite easily using a LinkedHashMap.

With this in mind you can create a new cache object backed by a LinkedHashMap that will have it's removeEldestEntry overridden, to check for the condition you want.

Since removeEldestEntry gets called every time you invoke put and putAll this will automitically refresh your cache and remove the unwanted entries.

akortex
  • 5,067
  • 2
  • 25
  • 57
1

I would recommend TreeSet

By default a TreeSet is orderd by the natural ordering of the elements you put, but can also pass your own Comparator

You can always check if your Set is at full capacity in your case size() == 10

Then if you need to add an 11th element, first you can pollFirst() or pollLast(), then add().

gtgaxiola
  • 9,241
  • 5
  • 42
  • 64