List
has a subList method that you can use:
Collections.max(arrayList.subList(0, 3))
There is no subList
for Collection
s in general, as not all collections are lists and, for some, the "first N elements" doesn't make a lot of sense, as they don't maintain any meaningful order (e.g. HashSet
).
You can take the first three elements of any Collection
(in whatever order the collection will provide), by iterating through it with a limit. It's probably best to use a stream for this:
yourCollection.stream().limit(3).collect(Collectors.toList());
Or you can find what you're looking for directly on the stream, without collecting the elements in some collection:
Optional<Integer> max = yourCollection.stream.limit(3).max(Comparator.naturalOrder());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…