1

I have a map setup like this:

Map<Integer, Set<Long>> myMap = new HashMap<Integer, Set<Long>>();

I'm trying to add my very first value to myMap like this:

myMap.put(1, myMap.get(1).add(myLong));

And java returns this:

The method put(Integer, Set<Long>) in the type Map<Integer, Set<Long>> is not applicable for the arguments (int, boolean)

nullByteMe
  • 6,141
  • 13
  • 62
  • 99

4 Answers4

6

Set.add returns a boolean indicating whether the set was changed. Change your code to:

myMap.get(1).add(myLong);

(as long as you know that myMap.get(1) already exists). If myMap.get(1) may not yet exist, then you need to do something like this:

Set<Long> set = myMap.get(1);
if (set == null) {
    set = new HashSet<Long>(); // or whatever Set implementation you use
    myMap.put(1, set);
}
set.add(myLong);
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • I was asking how to do this in another question and that's what they told me to do. Did I do something wrong? http://stackoverflow.com/questions/18131409/how-can-i-get-a-set-of-values-from-a-value-in-a-map?noredirect=1#comment26551780_18131409 – nullByteMe Aug 08 '13 at 17:17
  • @code4me - I can't track how you got from the last question to this one. But in any case, I've shown code how to add values in the case that no `Set` yet exists in the map. – Ted Hopp Aug 08 '13 at 17:22
3

Ted's answer is correct.

Not knowing the details of your task, you may want to consider a SetMultimap for this. It treats the value part of the map as a collection

SetMultimap Javadoc

Related Stack Overflow answer

Community
  • 1
  • 1
2

The add method you call doesn't return the Set itself, it returns a boolean.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

That is because the add method returns boolean value and the compiler feels that you are trying to add boolean value rather than a set. When you sequentially chain multiple method calls using '.' dot operator, the value returned by the last method is used for assignment. In this case last method was add() which returned boolean value, and hence compiler complained about adding wrong value in the map.

Instead try this :

Map<Integer, Set<Long>> myMap = new HashMap<Integer, Set<Long>>();
    if (myMap.containsKey(1)) {
        Set<Long> set = myMap.get(1);
        set.add(myLong);
    } else {
        Set<Long> set = new HashSet<Long>();
        set.add(myLong);
        myMap.put(1, set);
    }
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
  • This will fail if `myMap.get(1)` returns `null`. If it doesn't return `null`, then the last line is unnecessary. – Ted Hopp Aug 08 '13 at 17:23
  • Correct. The example was to just resolve his compilation error. It is not a full fledged working example. Still I will update the code. – Ankur Shanbhag Aug 08 '13 at 17:25