Suppose I define the following statement, will an array of dictionaries (key-value pairs) be created, with all keys initialized to "stringvalue1" and values to stringvalue2?
String exampledatastruct[] = { "stringvalue1", stringvlaue2 };
Is the above statement a bad way of using?
The above Collection type is unsuitable for keyed access. Use a Map:
Map<String, String> map = new HashMap<>();
map.put("stringvalue1", stringvlaue2);
That would simply give you an array with two String elements in it. The first would be the string "stringvalue1", the second would be whatever String the variable stringvalue2 references. There'd be no relation between the two, other than the fact they're in the same array.
What you wrote is an array, not a dictionary. A usual representation of java dictionary is java.util.Map. For example:
Map<String, String> dictionary= new HashMap<String, String>();
you would put values in the dictionary in this way:
dictionary.put("key", "value");
and would get values from the dictionary in this way:
String value= dictionary.get("key");
You are creating a String array, not an associative array. You should use the java Map interface. Also, you can only have 1 key "stringvalue1".
Related
I'm checking to see if a key in my HashMap exists, if it does, I also want to check to see if any other keys have a value with the same name as that of the original key I checked for or not.
For example I have this.
System.out.println("What course do you want to search?");
String searchcourse = input.nextLine();
boolean coursefound = false;
if(hashmap.containsKey(searchcourse) == true){
coursefound = true;
}
This checks to see if the key exists in my hashmap, but now I need to check every single key's values for a specific value, in this case the string searchcourse.
Usually I would use a basic for loop to iterate through something like this, but it doesn't work with HashMaps. My values are also stored in a String ArrayList, if that helps.
You will want to look at each entry in the HashMap. This loop should check the contents of the ArrayList for your searchcourse and print out the key that contained the value.
for (Map.Entry<String,ArrayList> entries : hashmap.entrySet()) {
if (entries.getValue().contains(searchcourse)) {
System.out.println(entries.getKey() + " contains " + searchcourse);
}
}
Here are the relevant javadocs:
Map.Entry
HashMap entrySet method
ArrayList contains method
You can have a bi-directional map. E.g. you can have a Map<Value, Set<Key>> or MultiMap for the values to keys or you can use a bi-directional map which is planned to be added to Guava.
As I understand your question, the values in your Map are List<String>. That is, your Map is declares as Map<String, List<String>>. If so:
for (List<String> listOfStrings : myMap.values()) [
if (listOfStrings .contains(searchcourse) {
// do something
}
}
If the values are just Strings, i.e. the Map is a Map<String, String>, then #Matt has the simple answer.
I have a Java array of type double with variable names used to store values as so:
double [] countArray = {teaCount, hotMealCount, drinkWaterCount, phoneCallCount};
I am looking to print the names of the variables out by it's index.
e.g. If I request countArray[0] it would return teaCount instead of the double that's stored.
If you want the names you need to store these
String[] countArray = {"teaCount", "hotMealCount", "drinkWaterCount", "phoneCallCount"};
Though most likely you wanted a Map<String, Double> such as
Map<String, Double> map = new LinkedHashMap<>();
map.put("teaCount", teaCount);
map.put("hotMealCount", hotMealCount);
map.put("drinkWaterCount", drinkWaterCount);
map.put("phoneCallCount", phoneCallCount);
This stores both the name and the value it has.
You can't do it the way you want but the Map coould be your solution:
Map<String, Double> count = new HashMap<String, Double>();
count.put("teaCount", 1.5);
count.put("hotMealCount", 2.5);
// etc
count.get("teaCount"); // 1.5
What you want to do is not possible with this approach. A solution would be to have a Map<String, Double> where you store the name as key and the count as the value in the Map.
Actually the variable name is something temporarily and you cannot access the name later. And if you add something to an array you do not add the variable by name to the array but the value location.
Yor are storing Strings, not double values in the array.
If you want to print the value of an index, just use:
System.out.println(countArray[0]);
And that will print teaCount.
Hope it works.
I get a list of object arrays that I need to group. The arrays contain different types of objects.
Here is an example:
List<Object[]> resultList = query.getResultList(); // call to DB
// Let's say the object array contains objects of type Student and Book
// and Student has a property Course.
// Now I want to group this list by Student.getCourse()
Map<String, Object[]> resultMap = resultList.stream().collect(Collectors.groupingBy(???));
What do I provide to the Collectors.groupingBy() method ?
The Student object is at index 0 in the object array.
groupingBy will by default give you a Map<String, List<Object[]>> in your case, because you will group arrays based on their student's course value.
So you need to group by the course value of the student in the array. The function you will apply will hence be:
o -> ((Student)o[0]).getCourse()
thus the grouping by implementation becomes:
Map<String, List<Object[]>> resultMap =
resultList.stream().collect(groupingBy(o -> ((Student)o[0]).getCourse()));
As an aside, you may want to use a class to have typed data and to avoid the cast, that could possibly throw an exception at runtime.
You could also perform the grouping by at the database level.
I have a HashSet of Strings in the format: something_something_name="value"
Set<String> name= new HashSet<String>();
Farther down in my code I want to check if a String "name" is included in the HashSet. In this little example, if I'm checking to see if "name" is a substring of any of the values in the HashSet, I'd like it to return true.
I know that .contains() won't work since that works using .equals(). Any suggestions on the best way to handle this would be great.
With your existing data structure, the only way is to iterate over all entries checking each one in turn.
If that's not good enough, you'll need a different data structure.
You can build a map (name -> strings) as follows:
Map<String, List<String>> name_2_keys = new HashMap<>();
for (String name : names) {
String[] parts = key.split("_");
List<String> keys = name_2_keys.get(parts[2]);
if (keys == null) {
keys = new ArrayList<>();
}
keys.add(name);
name_2_keys.put(parts[2], keys);
}
Then retrieve all the strings containing the name name:
List<String> keys = name_2_keys.get(name)
You can keep another map where name is the key and something_something_name is the value.
Thus, you would be able to move from name -> something_something_name -> value. If you want a single interface, you can write a wrapper class around these two maps, exposing the functionality you want.
I posted a MapFilter class here a while ago.
You could use it like:
MapFilter<String> something = new MapFilter<String>(yourMap, "something_");
MapFilter<String> something_something = new MapFilter<String>(something, "something_");
You will need to make your container into a Map first.
This would only be worthwhile doing if you look for the substrings many times.
I have the following list:
List<ArrayList> list;
list.get(i) contains the ArrayList object with the following values {p_name=set1, number=777002}.
I have to create a
Map<key,value>
where the key contains the p_name, and values are the numbers.
How to do it easily and fast as there can be hundreds of entries in the initial list and each number can be present in multiple p_name entries.
Update: Here is my current solution
List<Row> list; //here is my data
Map<String,String> map = new TreeMap<String,String>();
for (Row l : list) {
if (l.hasValues()) {
Map<String, String> values = l.getResult(); // internal method of Row interface that returns a map
String key = values.get( "number");
map.put(key, values.get( "p_name" ));
}
}
The method works, but maybe it could be done better?
PS : There is an obvious error in my design. I wonder if you find it :)
Sine the key can have more then one values, what you are looking for is a MultiMap. Multimap
Or a simple map in the form
Map<Key,ArrayList<Values>>
There is no "fast" way here to me. You still need to iterate through all the elements and check all the values.
And actually hundreds to Java is not much at all