Assign a name to every element of an array? - java

Is it possible to assign a name to every element of an array? For example in an array myArr[5], can I give myArr[0] the name "First", myArr[1] "Second" and so on? And if not, what might be a feasible way to achieve a similar result?

Use a Map:
Map<String, Whatever> yourMap = new HashMap<>();
yourMap.put("First", something);
yourMap.put("Second", somethingElse);
Then, to get elements out:
System.out.println(yourMap.get("First")); // prints something.toString()
System.out.println(yourMap.get("Second")); // prints somethingElse.toString()
// etc.
But if you're just going to use "First" and "Second" as keys, you're probably better off just using an array. Maps are useful when it's more convenient to access things using arbitrary objects rather than simple integers as keys.

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

How to iterate and remove keys from Map<String , Map<String, Set<String>>>

I am having map this way,
Map<String, Map<String, Set<String>>> sampleMap = new Map<String, Map<String, Set<String>>>();
and the data in this map would be this way,
sampleMap={2014={A=[1, 2], B=[3], 2015={A=[1,2], B=[1,2], 2016={A=[1,2], B=[3,4]}};
I want to remove the key's from the map based on this input: List<String> filter; with values this way,
filterArray : [2014, 2015]
i.e, first iterate through arraylist values one by one, verify if the arraylist value matches with any of the key in Hashmap.
if key is matched ignore it.
if key is not matched, I just want to remove that key from the map.
i.e, I always want to keep only matched keys in map, comparing with the input value passed.
In this case, as I have arraylist values this way,[2014,2015],
2014,2015 keys only to be in my map. So,
Data to be before removal:
sampleMap={2014={A=[1, 2], B=[3], 2015={A=[1,2], B=[1,2], 2016={A=[1,2], B=[3,4]}};
Data to be after removel:
sampleMap={2014={A=[1, 2], B=[3], 2015={A=[1,2], B=[1,2]}};
I tried this way, However I just want to know is this is the correct approch, or is it is prone to any of the exceptions?
Iterator<Map.Entry<String , Map<String, Set<String>>>> iter = sampleMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String , Map<String, Set<String>>> entry = iter.next();
logger.info("Keys : " + entry.getKey());
if (filterArray.equalsIgnoreCase(entry.getKey())) {
iter.remove();
}
}
Use retainAll() on the keySet:
map.keySet().retainAll(list);
Seems reasonable. I might have a couple pieces of advice.
First of all, whenever I see nested collections I always wonder if there should be a class or two in there. If this is a one-time task then don't worry about it, but if you want to reuse this code you might want to think about creating a class for your inner map/set... but if it's really this simple then it's no big deal.
Secondly if you are using Java 8, using a list comprehension for filtering would perform better (Because it would automatically thread your compares) and would be cleaner. I can give you the groovy solution for what you are trying to do, but I'm not familiar enough with java 8 list comprehensions to do it correctly.
def filteredStructure=structure.findAll{entry->entry.key.equalsIgnoreCase("2014") || entry.key.equalsIgnoreCase("2015"))
The java version should be really similar.

Trouble putting only unique values into an array

So I have a list of countries that I am reading from a text file and some of the countries are on there more than once. I need to put each country name into a string array without any doubles, or countries put on there twice. I tried using a for loop but could not wrap my head around the logic required for this.
Thanks in advance.
Try using a Set. A Set can contain one and not more than one of a particular instance (instance1.equals(instance2) will not be true).
Instantiate a Set like so:
Set<String> s = new HashSet<String>();
Then use a for loop to add the values.
String[] countries = {"JP", "US", "CN", "RU", "RU"}; //just make pretend these were read from a file.
for (String countryName: countries){
s.add(countryName); // RU will only be added once
}
System.out.println(s);
Outputs: [JP, US, RU, CN]
There are three different ways I can see this working:
Use a Set. This is the most efficient and easiest, and uses code that works
Each time you read in an element, iterate through the array, and see if the array already contains the element. If it does, don't add it. If you can't use Sets, this is the easiest code to write.
Read in all of the elements, sort the array. Iterate through the array, and if the current element doesn't equal the previous element, then add it to a new array. This is more efficient than #2 (O(nlog(n)) vs O(n^2)), but will require more code.
In order to check to see if a country is in the array, use an if statement. As you read in each country this checks to see if if exists in the array. If it doesn't, it adds the country to the array.
if(!Arrays.asList(yourArr).contains(country)){
yourArr[i] = country;
}

2 Dimentional array with Hash-map

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?

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

Categories