Robert kussmann
Robert kussmann

Reputation: 3

map.get(key) returning true instead of value

This is my first time asking on this site, so hopefully I didn't mess up any of the formatting. Anyway, I am having some trouble with getting the value from a key/ value pair from a map. I initially pair the key (1 of possibly many substrings of String "word") with an abstract HashSet to hold "word" However, when I try to print out the value paired with the key, I was expecting it to return the set. I receive "true" instead. Any advice as to how I would print out the set of words? Do I have to make the set non-abstract for this to work?

Thank you in advance for your help!

/**
 * Method that is used to load a file containing a list of words
 *
 * @param fileName the name of the file containing words
 *                 either is .txt or .csv format
 */
@Override
public void initialize(String fileName) {
    File file = new File(fileName);
    String word;

    try {
        Scanner scan = new Scanner(file);
        while (scan.hasNext()) {
            word = scan.next();

            for (int i = 0; i <= word.length(); i++) {
                wordMap.putIfAbsent(word.substring(0, i), new HashSet<>().add(word));

                System.out.println(wordMap.get(word.substring(0, i)));
                }
            }
        } catch(IOException e){
          //Exception handling stuff
        }
    }

Upvotes: 0

Views: 1193

Answers (3)

sprinter
sprinter

Reputation: 27976

Your map should be declared as:

Map<String,Set<String>> wordMap = new HashMap<>();

And then inside your loop:

String key = word.subString(0, i);
wordMap.putIfAbsent(key, new HashSet<>());
wordMap.get(key).add(word);

Upvotes: 0

phoenix
phoenix

Reputation: 38

When you are trying to do new Hashset, it is returning boolean,it gives compilation error itself. You can trying doing this:

for (int i = 0; i <= word.length(); i++) {
            HashSet<String> hs=new HashSet<>();
            hs.add(word);
            wordMap.putIfAbsent(word.substring(0, i), hs);
           // wordMap.putIfAbsent(word.substring(0, i), new HashSet<>().add(word));

            System.out.println(wordMap.get(word.substring(0, i)));
         }

Upvotes: 0

that other guy
that other guy

Reputation: 123550

Here's the API docs for HashSet.add:

public boolean add(E e)

Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

So in other words, new HashSet<>().add(word) is always the boolean true and that's what you're adding.

To create a new HashSet with one element in one expression, you can use new HashSet<>(Collections.singleton(word))

Upvotes: 2

Related Questions