user840718 user840718 - 10 months ago 35
Java Question

What is the fastest way to get the longest LinkedList in a LinkedList of LinkedList?

My data structure is a List of Lists, precisely,

LinkedList<LinkedList<String>>


Since I have some lists, I just want to find the list which has the bigger size.
What is the fastest way?

Answer Source

The LinkedList class in Java contains operations that you normally wouldn't have in a typical linked list. One case is being able to call size() on a LinkedList object. This is because the class inherits from the AbstractCollection interface. Therefore, you can just do something like this to find the biggest list:

int largest = -1;
LinkedList<String> largestLinkedList = null;
for (LinkedList<String> ll : listOfLinkedLists) {
    if (ll.size() > largest) {
        largestLinkedList = ll;
        largest = ll.size();
    }
}