ShahrukhKhan
ShahrukhKhan

Reputation: 365

How to convert a Set<Set> to an ArrayList<ArrayList>

How would I add all the elements of a Set<<Set<String>> var to an ArrayList<<ArrayList<String>>? Of course I'm aware of the naive approach of just adding them.

 private static ArrayList<ArrayList<String>> groupAnagrams(ArrayList<String> words){
              ArrayList<ArrayList<String>> groupedAnagrams = new ArrayList<>();
              AbstractMap<String, String> sortedWords = new HashMap<>();
              Set<Set<String>> sameAnagramsSet = new HashSet<>();
              for(String word : words){
                  char[] wordToSort = word.toCharArray();
                  Arrays.sort(wordToSort);
                  sortedWords.put(word, new String(wordToSort));
              }
              for(Map.Entry<String, String> entry: sortedWords.entrySet() ){
                  Set<String> sameAnagrams = new HashSet<>();
                  sameAnagrams.add(entry.getKey());
                  for(Map.Entry<String, String> toCompare : sortedWords.entrySet()){
                      if(entry.getValue().equals(toCompare.getValue())){
                          sameAnagrams.add(toCompare.getKey());
                      }
                  }
                  if(sameAnagrams.size()>0){
                      sameAnagramsSet.add(sameAnagrams);
                  }
              }

            //-->this line does not work!  return new ArrayList<ArrayList<String>>(sameAnagramsSet);

          }

Upvotes: 3

Views: 1359

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234795

Since you want to convert each element from a Set to an ArrayList, you'll have to do at least a little of this with an explicit loop, I think (unless you're using Java 8 or a third-party library):

Set<Set<String>> data = . . .

ArrayList<List<String>> transformed = new ArrayList<List<String>>();
for (Set<String> item : data) {
    transformed.add(new ArrayList<String>(item));
}

Note that I changed the type of the transformed list from ArrayList<ArrayList<String>> to ArrayList<List<String>>. Generally it's preferable to program to an interface, but if you really need a list that must contain specifically instances of ArrayList, you can switch it back.

Upvotes: 1

assylias
assylias

Reputation: 328598

With Java 8, you can do:

return sameAnagramsSet.stream()
       .map(ArrayList::new)
       .collect(toList());

although it returns a List<ArrayList<String>>.

What it does:

  • .stream() returns a Stream<Set<String>>
  • .map(ArrayList::new) is equivalent to .map(set -> new ArrayList(set)) and basically replaces each set by an array list
  • collect(toList()) places all the newly created lists in one list

Upvotes: 6

Related Questions