# anagram

```java
import java.util.*;

public class Main {
    static void printAnagramsTogether(String words[], int n) {

        //1. creating HM - Grouping Anagrams

        HashMap<String, ArrayList<String>> map = new HashMap<>();

        for(String word : words){
            String sortedWord = strSorting(word); 

            ArrayList<String> curr = map.getOrDefault(sortedWord,new ArrayList<>());

            curr.add(word);
            map.put(sortedWord, curr);            
        }

        // 2 . Collecting first element of each Group so that we can obtain lexo order

        ArrayList<String> firstElem = new ArrayList<>();

        for(String key : map.keySet()){
            ArrayList<String> curr = map.get(key);

            firstElem.add(curr.get(0));
        }

        //3. print groups in lexo order

        Collections.sort(firstElem);

        for(String word : firstElem){
            String key = strSorting(word);

            ArrayList<String> curr = map.get(key);

            for(String anagram: curr){
                System.out.print(anagram+" ");
            }
        }
        
    }

    public static String strSorting(String str){

        char[] chArr = str.toCharArray();

        Arrays.sort(chArr);

        String ans = String.valueOf(chArr);
        return ans;
    }


    // Driver program to test above functions
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String[] wordArr = new String[n];
        for (int i = 0; i < n; i++)
            wordArr[i] = sc.next();
        sc.close();
        printAnagramsTogether(wordArr, n);
    }
}
```
