3

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 :)

Community
  • 1
  • 1
Koerr
  • 15,215
  • 28
  • 78
  • 108
  • 3
    What do you want to happen when the size limit is exceeded? (should the add fail? should elements be removed to make room? if you want to remove elements, what's the criteria for removal?) – Mark Elliot Oct 31 '10 at 03:07
  • Possible duplicate of [Define a fixed-size list in Java](https://stackoverflow.com/questions/5207162/define-a-fixed-size-list-in-java) – nabster Oct 05 '18 at 05:03

3 Answers3

13

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());
Martin Forte
  • 774
  • 13
  • 17
0

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.

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
0
List b = new ArrayList<>(a.subList(0, 10));
Splash
  • 106
  • 6