List<Dictionary> DictionaryList= new ArrayList<Dictionary>();
I created ArrayList object, i need to store multiple name with keys and want to display name along with keys. How can i do it. Please help me
You should consider using Map<K,V> instead.
Considering you need a String to String mapping, a Map can be instantiated as :
Map<String, String> mapOfNames = new HashMap<String, String>();
Insertions are as easy as :
mapOfNames.put(key, name);
And retrievals :
String name = mapOfNames.get(key);
Now considering that there might be multiple values associated with the same key, you will have to modify the Map to a HashMap<String, List<String>>. That is, each key will correspond to a list of values.
So the definition will then be of the form :
Map<String, List<String>> mapOfNames = new HashMap<String, List<String>>();
Insertion :
mapOfNames.get(key).add(name);
Retrieval :
List<String> retrievedNamesForKey = mapOfNames.get(key);
More about HashMaps can be found here : HashMap (Java Platform SE 7 )
I think the object you are looking for is a map
consider the java 7 HashMap
HashMap<String,Value> map = new HashMap<String,Value>();
Insert an object for Value in your implementation.
Add a key value pair... The key is whatever you are using for the value
map.put("name1",23);
Now lets access one of those entries
map.get("name1"); // returns 23
Using parameterized classes is simple once you get the hang of it. See the Docs
Make sure you use objects to specify the pairs
So with this example use Integer() for numbers not int
Related
Using Java8/Collections/
I want to add data in Map in collections as:
Map<String,Map<String,Double>> OuterMap=new LinkedHashMap<String,Map<String,Double>>();
Inner map:
Map<String,Double> InnerMap=new LinkedHashMap<String,Double>();
OuterMap.put("Str1",InnerMap);
OuterMap.put("Str2",InnerMap);
The issue is I want to check the keys of InnerMap and it may vary to each other in InnerMap.
When I compare the keys of InnerMap. The OuterMap overrides the previous elements of the map.
I want the output like:
Str1={"SNP1"=0.3,"SNP2"=0.56,"SNP3"="0.76"} , Str2={"SNP1"="0.16","SNP2"=0.56,"SNP3"=0.78,"SNP4"=.56}
You should be creating new map instances when storing the values.
The simplest way to create a copy of the map is to use appropriate copy constructor:
Map<String,Double> innerMap=new LinkedHashMap<>();
outerMap.put("Str1", innerMap);
outerMap.put("Str2", new LinkedHashMap<>(innerMap));
Please also make sure you adhere to Java naming conventions: camelCase for variables/fields/methods, UpperCamelCase for classes/interfaces/enums.
I am currently working on Data Structures for writing a program on encryption and decryption of names. I have a doubt in Map interface. Actually to get the value associated with a key we have get() method in Map interface. But how to retrieve the key of a particular value without iterating through all the key value pairs in Map interface
Thank you
As others have said, it can't be done. The Map interface and its implementations do not support that.
Consider using a BiMap such as the one inculed in Google Guava Collections. It establishes a one-to-one (bidirectional) relationship between keys and values.
https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap
Using BiMap you can use Key key = biMap.inverse().get(value) to get a key for a given value.
Given that values are unique, you could to it like this:
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
String key = map.entrySet().stream().
collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))
.get("value1");
System.out.println(key); //gives key1
how to retrieve the key of a particular value without iterating through all the key value pairs in Map interface
Key is Key, not the value. You cannot do it. That's not how Map implemented.
Even If you make it with some magic (iterating multiple times, checking for equls etc ..), that's not guaranteed to give expected result..
And as per the definition of Map, Key is unique not the value. So there will be duplicated values and when you get by value, which associated key you will expect to get ?
If you are sure that there are no duplicates, you can do
for (Entry<Integer, String> entry : testMap.entrySet()) {
if (entry.getValue().equals("c")) {
System.out.println(entry.getKey());
}
}
Well like everyone said, you can't really do it in a decent way because there can be duplicate values. You could search for a hit using the equals() method and compare values. but then again, why are you even using a key/value map if you wanted to do such a thing.
in short, you could write your own version of the get method, taking in a instance of the value object you are trying to get. But there really is not a point in using a map if you are going to do that.
Why not use a list of some sorts of you desire to search on value ?
You can not do that because the "values" can be duplicated.
As said, that is not provided by Java-Map interface, since you should have a key and get the value then.
Usually you have something like this.
User user = ...;
HashMap<String, User> usernamesToUser = ...
Then you can get the key by something like:
String username = user.getUsername();
So without using the map actually.
However what you can do is, if the key is not directly to retrieve from the object you can use two Maps for both directions. So consider former example (just assume User the User object does not safe the Username)
Map<User, String> userMapReverse = ....;
Map<String, User> userMap = ....;
String username = userMapReverse.get(user);
However this option requires that you maintain two maps, which can be pretty ugly sometimes.
I have made the hash table below but Now I am trying to store multiple values with the same key but I am unable to do that please advise how to achieve that and then how to iterate overit to show the values attached with the multiple key..
Hashtable companies = new Hashtable();
// Java Hashtable example to put object into Hashtable
// put(key, value) is used to insert object into map
companies.put("Google", "United States");
companies.put("Nokia", "Finland");
companies.put("Sony", "Japan");
I want to achieve like ..
Hashtable companies = new Hashtable();
// Java Hashtable example to put object into Hashtable
// put(key, value) is used to insert object into map
companies.put("Google", "United States","France");
companies.put("Nokia", "Finland","Japan");
companies.put("Sony", "Japan", "indonesia");
folks please advise ..!!
You could use guava mutlimap (or) change your value to one of List implementation instead of String and better to use HashMap than HashTable.
Example:
Map<String, List<String>> = new HashMap<String, List<String>>();
You could use a map of lists...
Map<String, List<String>> companies = new Hashtable<String, List<String>>();
companies.put("Google", Arrays.asList("United States","France")); //etc...
Don't use Hashtable, use a HashMap.
If you use Guava (which you should, really ;)), use a Multimap.
If you don't, use a HashTable<String, List<String>>; you will need a wrapper class however so that you create the List in the key before you can add to that list.
Don;t use hashtable, use hashmap, you could just change the structure to this :
Map<String, List<String>>
I have a Map Map<Integer, List> with key, values. I need to convert this into List and pass it to the calling function. Once I have the list i need to convert this back to Map<Integer, List>
The reason I am converting the map to list is because i need to create webservice for this method. As I cannot expose the Map to webservice I need to convert this to list.
How to achieve this..?
A map has two functions called keySet() and values(). They return the keys and values of the map respectively. The keyes are returned as a Set and the values as a Collection.
You can create a list from either of these.
Here is an example:
Map<Integer, List> map = // map creation;
List<Integer> keyList = new ArrayList<Integer>(map.keySet());
List<List> valueList = new ArrayList<List>(map.values());
From what i read you are trying to pass map via list (as your service limitation).
In case you don't find any better solution, you can always use two lists. One for keys and one for values.
(but you are risking breaking map consistency with this approach).
You can create a class with two attributes (Integer, List) and create a List with one object by key.
Also, you can use:
new ArrayList(Map.entrySet());
and convert the resulting set to a list.
To get the values (Strings):
List<List<String>> listVals = new ArrayList<List<String>>(map.values());
To get the keys:
List<Integer> listKeys = new ArrayList<Integer>(map.keySet());
A map contains key value pair but list does not contains key value pair. So u can create a bean class to set key and values and then create list which contains objects of the bean class.
What I'm doing is storing classes into an ArrayList and retrieve them by its index number. But are there any list classes in Java where I can retrieve a list element by, lets say, its name? Like this:
ArrayList<string> myArr = new ArrayList<string>();
myArr.add( "ID_name", "String to store" );
ands then retrieve it by:
myArr.get( "ID_name" );
Also, are there any other alternatives to ArrayList? I need a list class to be optimized for:
Random access
Only need to push items into the list
Never need to delete anything from the list
If all you want to store is key-value pairs, and don't care about iteration order, I think you might like the HashMap class:
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
String bar = map.get("foo"); // bar is "bar"
You can use LinkedHashMap, so it will preserve the order, but you can extract elements by key as in regular map. Though you won't be able to extract entries by index.
An ArrayList is just that: an array. If you want to access values by something else than their indices, look for the various implementations of the Map interface (such as HashMap).
Use a Map<String, String>. In such structure, an element is added with a key. So you can get the element through the key:
Map<String, String> map = new HashMap<String, String>();
map.put("id", "string");
String s = map.get("id"); // s will be equals to "string".
As the other people have mentioned, a HashMap is probably what you want if you don't care about iteration order.
If you do, you can use a LinkedHashMap, which is really a HashMap bolted onto an LinkedList, giving you the best of both worlds: fast random access and preservation of iteration order.
Use a hashmap. You can add elements to a hashmap in much the same way as an arraylist. Also, you can create a set of keys ( 1 elements in the set per (key, value) pair)). You can then iterate over the set of keys.