Koerr
Koerr

Reputation: 15723

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

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

Upvotes: 4

Views: 17564

Answers (3)

Splash
Splash

Reputation: 126

List<Integer> b = a.size() > 10 ? new ArrayList<>(a.subList(0, 10)) : a;

Upvotes: 1

Martin Forte
Martin Forte

Reputation: 873

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());

Upvotes: 14

TofuBeer
TofuBeer

Reputation: 61526

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.

Upvotes: 1

Related Questions