Search code examples
javaif-statementhashmapset

How to test if a value is already in my HashMap while reading a file


I am working currently on a program to find similar sets. I need to map all my items contained in many sets in a HashMap with key, value pairs but I don't want redundant items to have many keys like key=1 value=bread and key=2 value=bread

So I wrote the following code

public static void main(String[] args) throws FileNotFoundException, IOException {
    // HashMap to stock all my items with keys that i will use for minhashing
    HashMap<Integer,String> hmap= new HashMap<>();
    List<List<Integer>> MinHash = new ArrayList<>();

    //to read my sets that i defined 
    FileReader in=new FileReader("C:\\items\\items.txt");
    BufferedReader brr = new BufferedReader(in);
    String item ; 
    int key=1; //for checking value pairs
    while( (item = brr.readLine()) != null)
        {
            System.out.println(hmap.containsValue(item));
            if(hmap.containsValue(item)){//problem
                System.out.println("Item already in my map");
            else{
                hmap.put(key, item);
                key++;
            }
        }
    System.out.print(hmap);
}

But this test doesn't seem to return value true even if i have already this value in my HashMap


Solution

  • Your code worked as is, just need an extra bracket "}" after your second "System.out" line.

    public static void main(String[] args) throws FileNotFoundException, IOException {
        // HashMap to stock all my items with keys that i will use for minhashing
        HashMap<Integer, String> hmap = new HashMap<>();
        List<List<Integer>> MinHash = new ArrayList<>();
    
        //to read my sets that i defined
        FileReader in = new FileReader("C:\\test\\items.txt");
        BufferedReader brr = new BufferedReader(in);
        String item;
        int key = 1; //for checking value pairs
        while ((item = brr.readLine()) != null) {
            System.out.println(hmap.containsValue(item));
            if (hmap.containsValue(item)) {//problem
                System.out.println("Item already in my map");
            }
                else{
                    hmap.put(key, item);
                    key++;
                }
            }
            System.out.print(hmap);
        }
    }
    

    Outputs: false false false false true Item already in my map {1=test, 2=blah, 3=asdf, 4=wefr}