【发布时间】:2014-06-12 12:01:28
【问题描述】:
我正在尝试找出一种方法来遍历文件并根据第一列生成新的哈希集。第一列中的值将作为哈希图中的键。例如,假设我有一个包含以下内容的文件:
- 元素1值1
- 元素1值2
- 元素1值3
- 元素2值1
- 元素2值2
我需要一个 hashmap,其中 key 为 element1,value 为 value1 value2 和 value3。下一个键将是 element2 和 value1 和 value2 的值。需要使用 User 类型的哈希集。
我可以通过 element1 并很好地填充它。但是当它到达 element2 时,我不确定如何在不擦除整个哈希集的情况下获取该信息。或者,由于文件的值不是静态的,因此动态生成新哈希集的最佳方法是什么。
当然,我们将不胜感激。
` 公共类用户{
public T Username;
String key = null;
public HashSet<User> friends = new HashSet<User>();
public HashSet<User> temps = new HashSet<User>();
HashMap<String, HashSet<User>> map = new HashMap<String, HashSet<User>>();
public HashSet readFile(){
String temp = null;
try
{
File f = new File("file.txt");
Scanner input = new Scanner(f);
String line = null;
line = input.nextLine();
int count = 0;
while (input.hasNextLine()){
String parts[] = line.split("\t");
temp = parts[0];
if(!parts[0].equals(temp)){
friends.add(new User(parts[1]));
map.put(parts[0], friends);
//here I had friends.clear(); thinking to clear out
//the set and start to populate with the values
//of new hashset but it clears set for all keys.
}else if(parts[0].equals(temp)){
friends.add(new User(parts[1]));
map.put(temp, friends);
}
temp = parts[0];
line = input.nextLine();
}
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
return friends;
}
public void setKey(String fKey){
key = fKey;
//return key;
}
public static void outputSet(HashSet<User> set){
Iterator<User> i = set.iterator();
while (i.hasNext()){
System.out.print(i.next() + " ");
}
System.out.println();
}
public void buildMap(String fKey, HashSet<User> mappy){
map.put(fKey, mappy);
System.out.println(map);
}
@Override
public String toString() {
return ("" + Username +"");
}
} `
【问题讨论】:
标签: java input hashmap hashset iteration