ArrayList in HashMap using a method in Java - 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);
}

Related

putting elements into a list of strings

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.

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

Complex Hashmap ArrayList Generator

Here's some code:
ArrayList<String> List = new ArrayList<>();
Map<String, List<String> > map = new HashMap<String, List<String>>();
List.add("stringA");
List.add("stringB");
List.add("stringC");
for(int i = 0; i<List.size();i++){
String key = List.get(i);
List<String> value = new ArrayList<String>();
map.put(key, value);
}
This code takes whatever is in the ArrayList, loops through it, adds it to the Map, and then creates an empty ArrayList with each string name as the variable name. Now, this works, but there's one problem, unless I'm overlooking something. At some point, I will need to access the new empty ArrayLists that are in the map. However, I won't know what the titles of these ArrayLists are, without printing them out, which I don't want to do. Basically, I'm thinking I need a map method or class and then an additional map key method or class. I'm not sure how to implement it but maybe something like this:
public class MapKey {
public MapKey(int count, String header){
}
}
Map<MapKey, List<String> > map = new HashMap<MapKey, List<String>>();
Another option I've considered is to somehow loop through the map array and add Strings to each ArrayList, but I'm very new to maps and looping through them. Especially ones that contain ArrayLists as their values.
There're multiple ways to access keys and values of your HashMap:
for (Map.Entry<String,ArrayList<String>> entry : map.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
// do your work
}
or
Set<String> keys = map.keySet();
for(String key : keys){
ArrayList<String> value = map.get(key);
}
Read the java HashMap api Java HashMap Link
Edit:
you dont need to loop through your outside ArrayList objects when you add all of its elements to another, just simply invoke addAll(), it will append all elements of an arraylist to another.
ArrayList<String> aList = map.get("stringA");
assume your first outside ArrayList is called outListOne;
aList.addAll(outListOne);
Appends to corresponding lists:
//assume number of outside lists are equal to number of map elements
String[] keysArr = {"stringA", "stringB", "stringC"};
ArrayList[] outLists = {outListOne, outListTwo, outListThree};
// adds outside lists to corresponding map ArrayList lists
for(int i = 0; i < keysArr.length; i++){
list = map.get(keysArr[i]); // you ArrayList in a map, get it by key name
list.addAll(outLists[i]); // append elements from out list to corresponding list
}
Not exactly sure what you mean by "titles of these ArrayLists." But here are a few code snippets that might give you a better idea of how to work with your map:
// add string x to the list for "stringA"
map.get("stringA").add(x);
// print all the values in the list for "stringC"
for (String s: map.get("stringC")) {
System.out.println(s);
}
// print the names of the lists that contain "xyzzy"
for (String key: map.keySet()) {
if (map.get(key).contains("xyzzy")) {
System.out.println(key);
}
}
// remove "foo" wherever it appears in any of the lists
for (List<String> list: map.values()) {
while (list.remove("foo")){}
}

Java, How to add values to Array List used as value in HashMap

What I have is a HashMap<String, ArrayList<String>> called examList. What I want to use it for is to save grades of each course a person is attending. So key for this HashMap is couresID, and value is a ArrayList of all grades (exam attempts) this person has made.
The problem is I know how to work with array lists and hashmaps normally, but I'm not sure how to even begin with this example. So how would I, or example, add something to ArrayList inside HashMap?
You could either use the Google Guava library, which has implementations for Multi-Value-Maps (Apache Commons Collections has also implementations, but without generics).
However, if you don't want to use an external lib, then you would do something like this:
if (map.get(id) == null) { //gets the value for an id)
map.put(id, new ArrayList<String>()); //no ArrayList assigned, create new ArrayList
map.get(id).add(value); //adds value to list.
String courseID = "Comp-101";
List<String> scores = new ArrayList<String> ();
scores.add("100");
scores.add("90");
scores.add("80");
scores.add("97");
Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
myMap.put(courseID, scores);
Hope this helps!
First create HashMap.
HashMap> mapList = new HashMap>();
Get value from HashMap against your input key.
ArrayList arrayList = mapList.get(key);
Add value to arraylist.
arrayList.add(addvalue);
Then again put arraylist against that key value.
mapList.put(key,arrayList);
It will work.....
First you retreieve the value (given a key) and then you add a new element to it
ArrayList<String> grades = examList.get(courseId);
grades.add(aGrade);
Java 8+ has Map.compute for such cases:
examList.compute(courseId, (id, grades) ->
grades != null ? grades : new ArrayList<>())
.add(value);
First, you have to lookup the correct ArrayList in the HashMap:
ArrayList<String> myAList = theHashMap.get(courseID)
Then, add the new grade to the ArrayList:
myAList.add(newGrade)
Can also do this in Kotlin without using any external libraries.
var hashMap : HashMap<String, MutableList<String>> = HashMap()
if(hashMap.get(id) == null){
hashMap.put(id, mutableListOf<String>("yourString"))
} else{
hashMap.get(id)?.add("yourString")
}
HashMap<String, ArrayList<ObjectX>> objList = new HashMap<>();
if(objList.containsKey(key))
objList.get(key).add(Object1);
else
objList.put(key, new ArrayList<ObjectX>(Arrays.asList(Object1)));

Categories