user972183
user972183

Reputation:

Best way to find the largest value in a Hashmap<Arraylist,Arraylist>

I have a hashmap as show here;

HashMap<ArrayList<Integer>,ArrayList<String>>

I'd like to find the ArrayList with the greatest length() from the second ArrayList (the value)

What is the most efficient way to do this?

Upvotes: 0

Views: 6006

Answers (2)

arshajii
arshajii

Reputation: 129507

You can loop over the map's values():

ArrayList<String> max = null;

for (ArrayList<String> list : map.values()) {
    if (max == null || list.size() > max.size())
        max = list;
}

To get the key associated with the largest value:

ArrayList<Integer> maxKey = null;
int maxLen = 0;

for (Entry<ArrayList<Integer>, ArrayList<String>> e : map.entrySet()) {
    int len = e.getValue().size();

    if (maxKey == null || len > maxLen) {
        maxKey = e.getKey();
        maxLen = len;
    }
}

Upvotes: 3

David Elliman
David Elliman

Reputation: 1389

Once the ArrayLists are in the HashMap you would have to enumerate them to find the one with the greatest length. However, you could use the SortedMap interface with keys being the length of each Array List as an additional index and then just pick the last one very efficiently at any time.

Upvotes: 0

Related Questions