Reputation: 47
There is an ArrayList
which stores integer values. Suppose the arrayList stored values are: 10, 20, 30, 40, 50
.
I know how to find the maximum value of the collection. I would have to do:
Collections.max(arrayList);
But what should I do to find the maximum of the first 3 elements of the collection? So in this example, it would be 30. Is there a sublist function for collections?
Upvotes: 1
Views: 1109
Reputation: 38245
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());
Upvotes: 5
Reputation: 11
You could make another array list in a method and store all the values you WANT so you could add 10, 20, 30 from the original array list, stop adding and then finding the max of that new array list with the 3 elements.
Hope this helped!
Upvotes: 1
Reputation: 51513
You can do the following:
public static void main(String[] arg) {
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
System.out.println(Collections.max(list.subList(0, 3)));
}
As ControlAltDel have pointed out in the comments use the subList method to extract the part of the list that you want to calculate the max.
From source one can read:
List subList(int fromIndex, int toIndex)
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (...)
Upvotes: 1