We can use a trie for the dictionary, then iterate through the trie and check the above conditions.
Sample:
import java.util.ArrayList;
import java.lang.String;
class AnagramsApp
{
public static void main(String[] args)
{
Anagrams an = new Anagrams();
an.getAnagrams();
an.displayOutput();
}
}
class Anagrams
{
String[] input={"tea","eat","ate","apple","java","vaja","cut","utc"};
ArrayList<String> output;
boolean[] match;
public Anagrams()
{
match=new boolean[input.length];
}
public void getAnagrams()
{
for(int i=0;i<input.length-1;i++)
{
for(int j=i+1;j<input.length;j++)
{
int a=0;
while(true)
{
String c= String.valueOf(input[j].charAt(a));
if(input[i].length()!=input[j].length())
break;
else if(input[i].contains(c))
{
a++;
if(a==input[i].length())
{
match[i]=true;
match[j]=true;
break;
}
}
else
break;
}
}
}
}
public void displayOutput()
{
for(int i=0;i<match.length;i++)
{
if(match[i]==true)
System.out.print(input[i]+" ");
}
System.out.println();
}
}