putting elements into a list of strings - java

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(""));
}
}

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);
}

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);

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.

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.

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.

Related

Hashmap arraylist (java)

Okay, so I'm fairly new to programming so apologies if this problem is really simple, I've created an ArrayList inside my Hash Map so that I can add more than one value into my hash map.
My code looks fine (to me) but theres an error on this line "mymap.add(module, new ArrayList>());" saying ( or [ expected.
Wasted way too much time trying to figure this out so thought I'd post here. Thanks in advance for any help. Also: yes I need to do it this way and no I can't use guava MultiMap.
public class hashArray {
HashMap<String, ArrayList<Integer>> mymap = new HashMap<String, ArrayList<Integer>>();
public hashArray() {}
public void addEntryHR( String module, Integer result ) {
mymap.add(module, new ArrayList<Integer>>());
There is a typo and a bug in your line:
// The typo is right here v
mymap.add(mod, new ArrayList<Integer>>());
Remove one of the > and change add to put:
mymap.put(mod, new ArrayList<Integer>());
The error you get, is about the typo. Fixing that typo will give you an error about add to be an unknown method.
You need to first get the list out from map object like below-
ArrayList<Integer> list = mymap.get(mod);
if (list==null){
//then create new ArrayList object and assign to list
list=new ArrayList<Integer>();
}
list.add(number); //adding new number to the list
mymap.put(mod,list); //storing in map
The problems
You create a new ArrayList in new ArrayList<Integer>>() (with contains a syntax error as well - a > too many), but never add number to it.
You are calling add on a HashMap, which doesn't have this method. For maps, it is called put.
Proposed solution
Please see the code below
Map<String, List<Integer>> myMap = new HashMap<>();
public void addEntryHR(String mod, Integer number) {
List<Integer> numbers = new ArrayList<>();
numbers.add(number);
myMap.put(mod, numbers);
}
Other remarks
Use interfaces
It is advised to use the interfaces of the collections rather than the implementations. This means Map<String, String> myMap instead of HashMap<String, String> myMap and List<Integer> instead of ArrayList<Integer>.
Why do this? Because this allows you to be flexible in the collections you use and reduce maintenance effort. Say you change your mind and want to use LinkedList instead of ArrayList, then you just have to change one new ArrayList<>() to new LinkedList<>() instead of all the ArrayList variables used throughout the code.

Merging n number of list into a Map based on a value in List

I have the following objects in an ArrayList and a value in this object is illustrated as the numbers at the beginning, which are Id of something.
I need to create a Map object, whose key should be the id of objects and whose values should be the objects with id. At the end of the day, I would like to have a Map something like that.
I have already solved this problem with two for loops and lots of if statements but it seems very ugly to me.
Any cleaner solution would be appreciated.
Map<Integer, List<Foo>> result = list.stream().collect(Collectors.groupingBy(Foo::getId));
Edited to fit the question edit, it is as simple as this:
ArrayList<Element> list = ...;
HashMap<Integer, List<Element>> map = new HashMap<Integer, List<Element>>();
for(Element e : list) {
ArrayList<Element> auxList;
if(map.contains(e.getId()) {
auxList = map.get(e.getId());
} else {
auxList = new ArrayList<Element>();
map.put(e.getId(), auxList);
}
auxList.add(e);
}
Just iterate over the starting list and add the elements to the map. If the map already contains the id, add it to the list. If not, create a new list.

return dictionary using hashmap java

I am very new to java had a question regarding returning the dictionary with the help of hashmap. The problem is I have string array let say with four names and I have to iterate and differentiate name according to the string length and if the key does not match I have to create other list and if it matches I have to simply append the string.
Basically the expected output should be like this
3:kel
4:john,aron
5:sonny
6:abraham
I tried little bit but stuck code looks like this
public static void main(String arg[])
{
HashMap<integer, ArrayList<String>> map = new HashMap<integer, ArrayList<String>>();
ArrayList<String> namelist = new ArrayList<String>();
obj.add("john");
obj.add("kel");
obj.add("abraham");
obj.add("sonny");
obj.add("aron");
map.put(3, namelist);
for (int i = 0; i < namelist.size(); i++) {
String element = namelist[i];
String nextElement = elements[i+1];
}
}
Your datatypes on the HashMap are not ideal. You want HasMap<Integer, List<String>>, although you could use String as a key if you call toString on the integer length of the name before using it as a key. Then, loop through the obj list and check if the length of the string you're on (obj[i].length()) exists in map using map.containsKey(obj[i].length()). If it does exist, you will map.get(obj[i].length()).add(obj[i]), and if it doesn't you will create a new ArrayList containing obj[i] and use the .put method on the HashMap to add it.
In the code you posted, first appears to not be defined.
I would rename obj to nameList, or something more descriptive. It's not an object.
Java 8's streaming capabilities offer a pretty elegant one-liner for this with the built in groupingBy collector:
Map<Integer, List<String>> map =
obj.stream().collect(Collectors.groupingBy(String::length));

how can we add (long,String) in arraylist?

I need to create a list with values of type - (long,String)
like -
ArrayList a = new ArrayList();
a.add(1L,branchName);
How can I do this because if I use list It will accept only int,String.
You should note that ArrayList's add(int,String) adds the String element in the given int index (if the index is valid). The int parameter is not part of the contents of the ArrayList.
Perhaps an ArrayList is not the correct choice for you. If you wish to map Long keys to String values, use Map<Long,String>.
Map<Long,String> a = new HashMap<> ();
a.put(1L,branchName);
You can define a custom class, e.g.
class IndexAndBranchName {
long index;
String branchName;
}
and then add instances of this to the ArrayList:
ArrayList<IndexAndBranchName> a = new ArrayList<>();
a.add(new IndexAndBranchName(index, branchName));
Whether you use this approach or something like Eran's depends upon what you need to use the list for subsequently:
If you want to look "branches" up by index, use a Map; however, you can only store a single value per key; you could use a Guava Multimap or similar if you want multiple values per key.
If you simply want all of the index/branch name pairs, you can use this approach.
You can use the below code for your question.
HashMap is also a better option , but if you want only ArrayList then use it.
List<Map<Object, Object>> mylist = new ArrayList<Map<Object, Object>>();
Map map = new HashMap<>();
map.put(1L, "BranchName");
mylist.add(map);

ArrayList in HashMap using a method in Java

I have a HashMap with ArrayList as values:
HashMap <String, ArrayList<String>> Test
ArrayList<String> fruit = new ArrayList<>();
fruit.add("bananas");
fruit.add("apples");
Test.put("fruit", fruit);
ArrayList<String> cities = new ArrayList<>();
cities.add("London");
cities.add("Paris");
Test.put("cities", cities);
I want to access the first element of each ArrayList, but using a method. For example something like that:
public String getSomething (ArrayList<String> Something) {
return (Test.get(Something)).get(1);
}
But this is not working as 'Something' must be an ArrayList. Any ideas about that? Is there another way of accessing a HashMap with multiple values for one key?
If you look at the Javadoc , you can see that HashMap has a method called values()
So you can retrieve the values and you just need to iterate on it.
Edit: The Java arrays and lists starting index is 0.
The method you have accepts an ArrayList arg but you are trying to pass the HashMap. Maybe you want something like this:
public String getSomething (HashMap<String, ArrayList<String>> map, String key, int n) {
ArrayList<String> something = (ArrayList<String>)map.get(key);
return something.get(n);
}

Categories