afraah
afraah

Reputation: 25

Map values being added to ArrayList

I'm having trouble understanding how the last line of code is valid.

class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
    if (strs.length == 0) return new ArrayList();
    Map<String, List> ans = new HashMap<String, List>();
    for (String s : strs) {
        char[] ca = s.toCharArray();
        Arrays.sort(ca);
        String key = String.valueOf(ca);
        if (!ans.containsKey(key)) ans.put(key, new ArrayList());
        ans.get(key).add(s);
    }
    return new ArrayList(ans.values());
}

}

The line of code: " return new ArrayList(ans.values());" Are the values being inserted one by one- what exactly is happening?

Upvotes: 1

Views: 141

Answers (3)

Desi boys
Desi boys

Reputation: 29

According to java doc ArrayList class has the constructor which can construct the list of elements from the specified collection. HasMap is also implementation of interface collection.

Upvotes: 0

Martino Nikolovski
Martino Nikolovski

Reputation: 159

ans.values() returns Collection<List<String>> and you need to return List<List<String>>. ArrayList class has constructor with Collection as a parameter, see the docs.

Upvotes: 0

Traian GEICU
Traian GEICU

Reputation: 1786

return new ArrayList(ans.values())
Break it down and see each instructions
1. new ArrayList - new object populated with some values
2 ans.values() - values coming from a collection: Map<K,V> and the method is returning all V.
Note V is List and all V should be a concatenation of all Lists (assume references)

Upvotes: 3

Related Questions