How to create and push dynamic elements in HashMap - java

static Map<Integer,HashMap<String,HashMap<String,String>>> maps = new HashMap<Integer, HashMap<String,HashMap<String,String>>>();
I want to insert the elements inside the HashMap I declared above , the inner most hashmap has values ready which I can use , now I am using it like ,
static Map<String,String> values = new HashMap<String, String>();
maps.put(1, new HashMap<<new String("")>, values>());
How can I achieve this ?

static Map<String,String> values1 = new HashMap<String,String>();
static Map<String,Map<String,String>> values2 = new HashMap<String,Map<String,String>>();
values2.put("", values1);
maps.put(1,values2);
btw, if you have java 7, you can use:
Map<String,String> values1 = new HashMap<>();
and so on for others

In cases you have map inside a map (inside a map), consider using Apache MultiKeyMap.
Coding will be more intuitive
It will improve the readability of your code
It will prevent many if(map.get(key) != null) blocks you will probably have in your code.

Why not to have instance of HashMap. When you wan to insert new value, you need to have Integer, String, String key and String value.
You continuously select nested HashMaps according to keys and then insert value to the most inner HashMap.
map.get(key1).get(key2).insert(key3, value)

Related

Is it possible to instantiate a Map with a list of keys?

Usually, if I know beforehand all the keys of a map, I instantiate it like this:
List<String> someKeyList = getSomeList();
Map<String, Object> someMap = new HashMap<String, Object>(someKeyList.size());
for (String key : someKeyList) {
someMap.put(key, null);
}
Is there any way to do this directly without needing to iterate through the list? Something to the effect of:
new HashMap<String, Object>(someKeyList)
My first thought was to edit the map's keyset directly, but the operation is not supported. Is there other way I'm overlooking?
You can use Java 8 Streams :
Map<String,Object> someMap =
someKeyList.stream()
.collect(Collectors.toMap(k->k,k->null));
Note that if you want a specific Map implementation, you'll have to use a different toMap method, in which you can specify it.

How could i make HashSet as parameter to the HashMap?

I have to maintain the list of indexes for each of the key value in HashMap.
So i declared HashMap as
HashMap<Integer,HashSet<Integer> hset = new HashSet<Integer>()> hm = new HashMap<Integer,HashSet<Integer> hset = new HashSet<Integer>()>();
but the above declaration seems to be not correct.
So i declared it as
HashSet<Integer> hset = new HashSet<Integer>();
but here the problem is,how could i declare the type of objects stored in HashSet i,e Integer, bacause in the above declaration the HashSet is rawtype.
I would like to add more here,
You need to initialize your outer Map like below
HashMap<Integer,HashSet<Integer>> map = new HashMap<Integer,HashSet<Integer>>();
and inner collection like this
HashSet<Integer> hset = new HashSet<Integer>();
And you insert the values like below in map and your hash set.
hset.add(1);
hset.add(2);
map.put(100,hset);
hset = new HashSet<Integer>();
hset.add(3);
hset.add(4);
map.put(101,hset);
So every time you need new instance of HashSet to put in map.
You can get inner HashSet by using Map key you used to insert.
HashSet<Integer> hset=map.get(100); //Same map
Here is your declaration should look like
HashMap<Integer,HashSet<Integer>> map = new HashMap<Integer>,HashSet<Integer>>
Second declaration you have provided for Hashset is correct. Its not raw type. Did you try adding a any other type of element to it ?
Try this it will work :
Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();
you can easily Set Using Map tag only .
or
Create the Object Of Hashmap and put the value from Refrence. it will work

iterate through all the values of a key in hashtable java

Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
ht.put(1,"student1");
ht.put(1,"student2");
How can I iterate through all values of "a single key"?
key:1
values: student1, student2
You need to use:
Hashtable<Integer, List<String>> ht = new Hashtable<Integer, List<String>>();
and add the new String value for a particular key in the associated List.
Having said that, you should use a HashMap instead of Hashtable. The later one is legacy class, which has been replaced long back by the former.
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
then before inserting a new entry, check whether the key already exists, using Map#containsKey() method. If the key is already there, fetch the corresponding list, and then add new value to it. Else, put a new key-value pair.
if (map.containsKey(2)) {
map.get(2).add("newValue");
} else {
map.put(2, new ArrayList<String>(Arrays.asList("newValue"));
}
Another option is to use Guava's Multimap, if you can use 3rd party library.
Multimap<Integer, String> myMultimap = ArrayListMultimap.create();
myMultimap.put(1,"student1");
myMultimap.put(1,"student2");
Collection<String> values = myMultimap.get(1);
A Hashtable doesn't store multiple values for a single key.
When you write ht.put(1, "student2"), it overwrites the value that goes with "1" and it is no longer available.
Hashtable doesn't allow multiple values for a key. When you add a second value to a key, you're replacing the original value.
If you want multiple values for a single key, consider using a HashTable of ArrayLists.

List Object with multiple "keys" in it

Hoi,
currently I have a List in Java where I add Entrys via list.add("Example");
But now I would like to add IDs to each entry. I could do this via
list.put("Example XY");
list.setData("Example XY", 1);
But in my lists there are a lot of duplicate "Names". So they Keys for the names get overriden because it seems that I cant set duplicate keys in it.
Somebody got an Idea how to solve it? Thanks a lot!
You should really think about using a ListViewer instead. A ListViewer can contain any bean object you want and show any of it's fields as the text in the List.
Here is an example of a ListViewer.
It's definitely a lot more code, but it will be worth it in the end.
Use a HashMap, if you would like to store the key - value pair in the collection
import java.util.HashMap;
public class Test1 {
public static void main( String [] args)
{
HashMap<String, String> map = new HashMap<String,String>();
map.put("1", "Example XY");
map.put("2", "Example XZ");
}
}
Note: you can not have duplicate values for key
You should look into MultiMap
Use MultiMap<String, String>
Multimap<String, String> myMultimap = ArrayListMultimap.create();
// Adding some key/value
myMultimap.put("E1", "One");
myMultimap.put("E1", "Two");
myMultimap.put("E1", "Three");
myMultimap.put("E2", "AnotherOne");
// Getting the size
int size = myMultimap.size();
System.out.println(size); // 4
// Getting values
Collection<string> sample = myMultimap.get("E1");
System.out.println(E1); // [One, Two, Three];
Hope this helps.
You have to consider what it means when an object has the same key. If it's not the same object than the key you are using is wrong. You could add the data to the objects instead of using strings and then have a list with multiples of each "name"
List l = new ArrayList<SomeObject>;
list.put(new SomeObject("red ball", 1))
list.put(new SomeObject("red ball", 2))
or make a map of lists of values
Map<String,List<SomeObject>> = new HashMap<String,List<SomeObject>>;
map.get("Red Ball")==null ? map.put(new ArrayList<SomeObject>(){{ add(x) }})
: map.get("Red Ball").add(x);
Personally I prefer solution 1.

Two-dimensional ArrayList

Just a very small question... I seem to run into too much complexity here: I have to realize an index-structure like {42, someString}. I tried:
Object entry[][] = new Object[1][1];
ArrayList<Object> my_list = new ArrayList<Object>();
However that looks really strange. Isn't there a better much simpler solution to just store some Integer and a String? I need to perfrom search for the Strings and return the Integer... so I thought Collections and ArrayLists are good friends in the Java API.
Solution: use a Map
Uhm, do you perhaps need a Map?
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("Some String", 42);
// or, more correctly:
map.put("Some String", Integer.valueOf(42));
You can search it using
Integer result = map.get("Some String");
Reference: Sun Java Tutorial > Collection Trail > Interfaces > The Map Interface
Fixing the OP's Code
BTW, the code in the question is flawed. Here's how you would do it if you wanted to use a List of object arrays (which you shouldn't):
// single dimension, not multi-dimension
Object[] entry = new Object[]{"Some String",Integer.valueOf(42)};
// use interface as variable, not implementation type
// generic type is object array, not object
List<Object[]> myList = new ArrayList<Object[]>();
// add array to list
myList.add(entry);
Now you could search like this:
for(final Object[] candidate : myList){
if("Some String".equals(candidate[0])){
System.out.println("Result: " + candidate[1]);
break;
}
}
However, this is just for reference, don't do it this way. The Collections Framework contains solutions for almost all standard cases. Use a Map.
Make a tuple class
public Class IntegerStringTuple {
private Integer number;
private String string;
//setters and getters etc.
}
If I understand correctly you should use a Map.
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(42, "someString");
String str = map.get(42);
Simply use a HashMap
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("foo",42);
why not use a map?
Map<String,Object>
It sounds like you want a Map
I would use a Map. Maps are used to store key value pairs.
Map<String, Integer> map = new HashMap<String, Integer>();
Map may not be used instead of an ArrayList when you require the order to be maintained.
ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
arr2.add(1);
arr2.add(2);
arr2.add(3);
arr1.add(arr2);
for(int i=0;i<arr1.size();i++){
System.out.println("i:"+arr1.get(i));
for(int j=0;j<((ArrayList)arr1.get(i)).size();j++){
System.out.println("j:"+((ArrayList)arr1.get(i)).get(j));
}
}
output: i:[1, 2, 3]
j:1
j:2
j:3
ArrayList<String> lcname = new ArrayList<String>();
lcname.add(cname);
ArrayList<String> lsize = new ArrayList<String>();
lsize.add(size);
Dictionary dictionary = new Hashtable();
Hashtable<String, ArrayList<ArrayList>> hashtable =
new Hashtable<String, ArrayList<ArrayList>>();
hashtable.put(fname, new ArrayList<>());
hashtable.get(fname).add(lcname);
hashtable.get(fname).add(lsize);
System.out.println(hashtable);
Here is the code for dictionaries of list(list).
OUTPUT
{file name=[[column name], [size]]}

Categories

Resources