简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM