2 Dimentional array with Hash-map - java

Is there a way to put a 2d array into a Hash map setup?
Example of the array would be two strings {"John", "red"},
{"George", "blue}
And I would want red to correspond to john etc.
I know I can use a nested loop to go through every item in the 2d array but how would then set it up to add them to the hash-map
hashMap.put("John", "red");

Assuming every array has 2 items in the form of {Name, Color}, you can just iterate over it
for(String[] combo : some2DArray){
someHashMap.Put(combo[0], combo[1]); // Or swap them, depending on what you
// want to be the key and the value
}
If you want to avoid the possibility of removing data because you happen to have two people with the same name there are a few approaches you can take:
Keep the old data
Keep the new data
Assign the new data to a new key
Combine the data in the same key
Keep the old data
Perform a check before using HashMap#put and see if the key already exists.
Only add the data if it doesn't exist yet.
Keep the new data
Use the current code, it will overwrite the old value.
Assign the new data to a new key
Create a new key based on your own rules and insert that.
Combine the data in the same key
Define your HashMap as HashMap<String, List<String>> and add the values to the list.

How about implementing a Pair class, so you can use HashMap<Pair<String,String>> ?
EDIT: Might be that I misunderstood your question, is that what yoe were asking?

Related

How do I assign names to variables in an arraylist?

I am doing a project for my AP Computer Science class. The current project asks us to create a rip off version of excel that prints to the console. I am wondering if theres a way for me to create an arraylist of empty values that I can assign cell names to (A1, A2, F6, etc.) and then use those names to call values from their place in the arraylist. For example, I'd give the cell D4 a value of 6, store that 6 in an arraylist, then call it back using "D6".
A link to the directions of the project: https://issaquahwednet-my.sharepoint.com/:w:/g/personal/stutlerk_issaquah_wednet_edu/EQOW8BFzHIhIsdvXGP-qKDsBbN7BFa-kUCiMeeq9BZbbwg?e=Nc1Jcs
Maybe I'm not making sense, for which I am very sorry.
//what i would like to be able to do:
arraylist "cells" = (A1 through L20)
user input = "A1 = hi"
set index "A1" of "cells" to "hi"
repeat that stuff until user input = quit
is this possible? or would I just have to create two arraylists, one for cell numbers and one for values? I guess I could do that and then if a user wants to see what a cell says then they could Say "A1" and I could search my cell arraylist for a value of A1 then compare that index with the other arraylist.
I'm completely lost one this and, again, sorry if I'm not making any sense.
To do what you want, you'd need a map rather than a list. Lists always have integer numbers as the indices and there's no way to change that. (You could technically do this with two arrayLists, but it would be a pain to maintain it so that "A1" and "hi" stayed in the same index on two different lists if you ever had to delete/move anything.)
The HashMap documentation is here: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
And you'd do something like this:
Map<String, String> cells = new HashMap<String,String>();
cells.put("A1", "hi");
That would create a key-value pair with key "A1" and value "hi".
You can use structure map where for every key you have associated a value.
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

Increment Key in a collection

I have a collection say
Map<Integer,Integer> myMap=new Map<Integer,Integer>();
myMap.put(1,"a");
myMap.put(2,"b");
myMap.put(3,"c");
My map currently has {1="a",2="b",3="c"}.
Suppose I want to put a value say myMap.put(1,"d")
So is there a way that I am able to add the existing key and incrementing the remaining key so my output map be like
{1="d",2="a",3="b",4="c"} ?
You will have to iterate over all the elements of the Map in order to modify the values for all the existing keys.
For example, woth Java 8 Streams you can produce a new Map where the keys are incremented, and then add the new Entry :
map = map.entrySet().stream().collect(Collectors.toMap(e->e.getKey()+1,e->e.getValue()));
map.put(1,"d");
However, if your keys are consecutive integers (as your example suggests), why not use an ArrayList<String> instead of a Map<Integer,String>? This will give you the functionality you want by simply calling list.add(0,"d"); (with the small difference of the indices starting at 0 instead of 1).

HashMap<String, Set<String>> cant find its key even though it exists

I have a HashMap of this type
Map<String, Set<String>> list_names = new HashMap<String,Set<String>>();
that I have constructed and added its elements from a txt file that has a list's name and a set of names in it.
98298XSD98 N9823923 N123781 N723872 ....
13214FS923 N9818324 N982389
... ...
I made another HashMap, called names_list that pretty much replaces the order of the list_names HashMap such that I can get all the lists that a given name is in.
now the HashMap I have is pretty big, and there are over 400k items and 60k lists.
somewhere in my code im trying to get the Set of different lists many many times and then getting the intersection of these two lists for computational purposes,
a_list = this.names_lists.get(a);
b_list = this.names_lists.get(b);
// printing lists
//intersection stuff
but whats weird is the HashMap didn't recognizance one of its keys(or maybe many of its keys) and treated it as null after one retrieval or sometimes 0 retrievals.
a:0122211029:[R3DDZP35ERRSA] b:1159829805:[R3ALX1GRMY5IMX, R1204YEYK4MBCA]
a:0122211029:[] b:1593072570:[R222JSDL42MS64]
here, im just printing the name and names_list.get(key).toString();
and yes i'm printing these before doing any intersection stuff.
any idea why is it doing that?
When you calculate the intersection of two sets, you actually modify one of the sets. You have to create a temporary set to hold the intersection, e.g.:
a_list = this.names_lists.get(a);
b_list = this.names_lists.get(b);
Set<String> intersection = new HashSet<>(a_list).retainAll(b_list);

Creating a HashMap as an index for title keywords to improve search efficiency

I have a custom class Disks which stores various information of CDs such as their Title, Length, Artist etc. These Disks objects are stored in an ArrayList which can only have elements of Disks added. I am using a method to search for these objects based on matching their title. It takes a user input and then goes through each element of the list and compares the user keyword and the Title of the CD. If it is a complete match, its information is then returned to the user.
I want to change this search mechanization slightly by incorporating a HashMap. I am looking to tokenize each Disks Title and then create a mapping entry for the keyword.
Here is an example: The word "Cars" appears in the titles of the ArrayList elements at position 0,5,7. I want to be able to create a mapping entry for "Cars" which will be a list [0,5,7]. If another element is added to the ArrayList at position 10 with "Cars" in the title, how would I amend the old mapping entry so the new list would be [0,5,7,10]?
In the end I want the user to search for title keywords “Loud Cars”. I will first find "loud" in the index to get a list of [0,7,5] (for example), and then find "cars" to get a list of [0,5,7,10]. Then, I will find where these lists intersect and return the ArrayList elements that correspond to these locations.
My current HashMap declartion looks like this: public HashMap<String, ArrayList<Integer>> map = new HashMap<>(); however even when the Key is different, the values stored in the ArrayList are the same because there is only one of them.
My Disks ArrayList is: public ArrayList<Disks> items; Would there be a way to incorporate this ArrayList into the Value of the HashMap?
Add a new value to the index entry for "Cars"
map.get("Cars").add(10);
Safe way to do this (key = "Cars", index = 10):
ArrayList<Integer> entry = map.get(key);
if (entry == null) {
entry = new ArrayList<Integer>();
map.put(key, entry);
}
entry.add(index);
Instead of using
HashMap<String, ArrayList<Integer>>
I'd recommend
HashMap<String, HashSet<Integer>>
Which is automatically avoids duplicates.
When you search for multiple words, use retainAll to build the intersection of multiple sets (but copy the first set because retainAll is destructive):
Set<Integer> resultSet = new HashSet<Integer>();
resultSet.addAll(map.get("Cars"));
resultSet.retainAll(map.get("Loud"));
You would need to create a new ArrayList of Integer for every string mapping to a value. The first time an entry is used, you create a new list (You must check that the string maps to null), and add the value of the index that the new Disk entry will be stored at in your ArrayList of Disls to you ArrayList of Integers. Any time the string maps to a non-empty list, then you just add the index (where it is in the Disk ArrayList) to the ArrayList of Integer.
Honestly, I think the best way for you to scale your solution is by using bloom filters or something sophisticated like this. This would require you to create complex hash codes, manage false positives, among other things.
Having that said, based on your design, I think what you can simply have a hash map pointing to the Disks objects that are also stored on the array list.
public HashMap<String, ArrayList<Disks>> map
For the keyword "cars", you have a list of Disks objects. For the keyword "loud" you have another list of Disks objects. Just take both lists and find the intersection, using the retainAll() method.
Make sure to override hashCode() and equals() in Disks so all collections will work fine.

How to perform a group by (sql) in Java

I have a text file which looks like this:
code appearance
----------------
j4t8 1
fj89 3
pf6n 1
j4t8 5
And I want to sort by the codes which appear the most. As you can see (and since I want to perform a group by) there are duplicate codes, so using HashMap would be a problem (duplicate keys). Any ideas?
don't know if this is the best solution but you could create a map of a list like this:
Map<String, List<Integer>> map = new HahsMap<String, List<Integer>>();
if(map.contains.(key))
{
map.get(key).add(new_appearance_value);
}
else
{
List<Integer> app = new ArrayList<Integer>();
app.add(new_appearance_value);
map.put(key, app);
}
Where the map key would be the code and the values of appearance would go into the list.
Note: to determine which code has more appearances just check for the size of the list of each code.
You can use
HashMap map = new HashMap<String, List<Integer>>();
The appearances will be stored in a list associated with every code.
Then given a code you just retrieve the list of integers and iterate over it.
You need a Collection of Pair objects. Each pair holds the code and the appearance. You then sort the collection using a Comparator, which only compares the appearance in each Pair object, and disregards the code.
The Commons Collections MultiValueMap can be used to decorate another map, allowing it to have more than one value for a key.

Categories