I prefer the more clever solution by WJS, but here is another solution as well. This one here is not as brief but might be easier to comprehend on first reading.
You said:
I have an array with multiple arraylists of different sizes. I want to find the index of the largest arraylist in the array.
As they discussed, Collections.max
returns you a reference to the largest object, not the the index of that object within the array.
So we need two steps:
- Determine the largest element.
- Get the index of that largest object.
First, some example data.
List[] arrayOfListsOfIntegers =
List.of(
List.of( 1 ) ,
List.of( 1001 , 1002 , 1003 , 1004 ) ,
List.of( 101 , 102 , 103 ) ,
List.of( 11 , 12 )
)
.toArray( List[] :: new );
Determine the largest element
Use Arrays.asList
to make a view onto that array that appears as a List
. This way we can call convenient List
methods.
Then make a stream of that list. Sort the elements of the stream by getting each one’s size. Make a new list from the sorted elements. We know the last element of that sorted list has the biggest element.
List sorted =
Arrays
.asList( arrayOfListsOfIntegers )
.stream()
.sorted( Comparator.comparingInt( List :: size ) )
.toList();
Get a reference to that biggest element, the last element of our sorted list of lists.
Object target = sorted.get( sorted.size() - 1 );
Get the index of that largest object
That target object is what we want to locate within our original list. We can locate by calling List#indexOf
. Here again we use Arrays.asList
to mask our array as a List
.
int index = Arrays.asList( arrayOfListsOfIntegers ).indexOf( target );