我已经开发了以下程序来使用 java 中的 Hashmap 打印字谜。但是无法弄清楚要在行内放置什么以map.put();
用于将条目插入到 hashmap 中。
import java.util.*;
class anagram
{
public static void main(String args[])
{
String temp;
int i,n;
Scanner s1=new Scanner(System.in);
List<Integer> temp2;
ArrayList<String> list=new ArrayList<String>();
HashMap<String,ArrayList<Integer>> map=new HashMap<String,ArrayList<Integer>>();
System.out.println("Enter the number of strings");
n=s1.nextInt();
//Input the strings and store them in Hashmap after sorting each
//string on character basis
//e.g hello , olleh are both stored as "ehllo" --> 0,1
//"ehllo" is sorted string and 0,1 are its keys
//In this way, at the end each bucket in hashmap will have anagrams
//which can be displayed on the basis of keys stored
for(i=0;i<n;i++)
{
temp=s1.next();
list.add(temp);
//what should I add here to input new string index into proper place
map.put();
}
//Iterating the hashmap to print values of each bucket
Iterator iterate=map.keySet().iterator();
while(iterate.hasNext())
{
Map.Entry entry=(Map.Entry)iterate.next();
temp2 =entry.getValue();
for(i=0;i<temp2.size;i++)
System.out.print(list.get(temp2.get(i))+" ");
}
list.clear();
}
//method to sort the string
private static String sort(String s)
{
char arr[]=s.toCharArray();
Arrays.sort(arr);
return String.valueOf(arr);
}
}