[英]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)我知道如何在 Map 中限制大小( 像这样,使用 LinkedHashMap.removeEldestEntry 方法就是这样做的)
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.
如果只有10个,则不应该是性能问题,请创建一个新列表。
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. 我将查看java.util.Collections类的源代码,并开发一个SizeLimitedList,类似于它们如何执行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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.