Reputation: 13
I need to insert some data into a Map that expects a String as the key and a List of Strings as the value, but I don't know how to do it.
Here is what I've tried to do.
First of all, I've created a HashMap, then I've created a new object, and now there's the problem.
I create a new List of Strings giving it a name, then I think that I have to use the "put" method, but it's wrong, as I have an error that tells: "The method put(String, List) in the type HashMap> is not applicable for the arguments (String, boolean)".
Why a boolean? When I type .put() in Eclipse, it tells me that it expects that the parameter is a "List value", ok, but how do I write that? Can you better explain me the problem? Thanks.
public class Main {
public static void main(String[] args) {
HashMap<String, List<String>> dizionarioMultilingua;
dizionarioMultilingua = new HashMap<String, List<String>>();
List<String> list = new ArrayList<>();
dizionarioMultilingua.put("dds", list.add(""));
}
}
Upvotes: 1
Views: 1104
Reputation: 3799
You need to add strings to your list before "putting" it in the Map.
List<String> list = new ArrayList<>();
list.add("");
dizionarioMultilingua.put("dds", list);
The call to "list" vs. "list.add("")" are very different in the sense that the first refers to the object List, while the second is just a method call that will return a Boolean.
Upvotes: 0
Reputation: 6082
ArrayList#add() returns boolean, so it appears like you are putting <String,Boolean>
, while expected is <String, List<String>>
what you have to do , is filling the Strings list first, then put it in the map
List<String> list = new ArrayList<>();
list.add("item1")
list.add("item2")
list.add("item3")
dizionarioMultilingua.put("dds", list);
Upvotes: 1
Reputation: 3570
There's a small mistake in your code. Since the put method require an String and a list, you should supply the list as the 2nd parameter. Not, list.add(""). List.add() return a boolean stating whether the element we specified was successfully added to the list.
public class Main {
public static void main(String[] args) {
HashMap<String, List<String>> dizionarioMultilingua;
dizionarioMultilingua = new HashMap<String, List<String>>();
List<String> list = new ArrayList<>();
list.add("");
dizionarioMultilingua.put("dds", list);
}
Upvotes: 1
Reputation: 382
The problem is here: dizionarioMultilingua.put("dds", list.add(""));
This is because list.add("")
returns boolean that indicates if element was succesfully added to list.
If you want to put your list into HashMap then firstly you should fill your list and then put it in.
Upvotes: 0
Reputation: 19168
Because, list.add(E e) returns a boolean value.
Firstly, you need to prepare your list by inserting multiple(or as many as you desire) String items to the list).
Then, at the last step, you should map that with the string.
Upvotes: 0