Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the number of entries in a java List?

Tags:

java

I know how to limit size in Map (like this,using LinkedHashMap.removeEldestEntry method does exactly that)

I want to know how to limit size in a List,what is a best way to implement?

thanks for help :)

like image 337
Koerr Avatar asked Sep 13 '25 18:09

Koerr


2 Answers

You could try create a new list with streams. If are only 10 don't should be a performance problem create a new list.

list = list.stream().limit(10).collect(Collectors.toList());
like image 178
Martin Forte Avatar answered Sep 15 '25 08:09

Martin Forte


I would look at the java.util.Collections class source and develop a SizeLimitedList similar to how they do a checkedList. Then on add I would delete the first entry from the list if the list was full.

like image 33
TofuBeer Avatar answered Sep 15 '25 09:09

TofuBeer