How to convert set to ArrayList

How to add all elements of set < < set < string > >? VaR to an ArrayList < < ArrayList < string > >? Of course, I know it's just a naive way to add 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);

          }

Solution

With Java 8, you can:

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

Although it returns list < ArrayList < string > >

What can it do:

> . Stream() returns stream < set < string > > Map (ArrayList:: new) is equivalent to Map (set – > New ArrayList (set)), basically replace each group with an array list > collect (tolist()) and put all newly created lists in one list

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>