【问题标题】:Using Java need to create a hashmap that is populated with data from a file使用 Java 需要创建一个填充有来自文件的数据的 hashmap
【发布时间】: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


    【解决方案1】:

    您似乎希望friends = new HashSet&lt;User&gt;(); 而不是friends.clear() 创建一个新列表。但是这段代码真的很乱,建议你去Code Review寻求帮助来清理它。

    【讨论】:

    • 感谢您的反馈。当我插入friends = new HashSet();我得到一个哈希图值: {element2=[value1, value3, value1, value2], element1=[value1, value3, value1, value2]} 这不是我想要的。哈哈...我知道我的代码一定看起来很糟糕。我目前处于“请工作”模式。我让它运行后会清理。
    • 嗯,我可以看到很多不起作用。我看看我能写什么。
    猜你喜欢
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 2022-10-22
    • 1970-01-01
    • 2011-03-24
    • 2021-02-16
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多