Filling Map - java - java

I have problem with filling a Map in Java, I think this is simple, but I can't resolve this.
Let's look at this:
Map<Integer, HashMap<String, String>> lineArrayData = new HashMap<Integer, HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
String singleData[];
int lineCounter = 0;
for ( String line : this.lines )
{
singleData = line.split("\\|\\|");
map.put("type", singleData[0]);
map.put("text", singleData[1]);
map.put("page", singleData[2]);
map.put("x", singleData[3]);
map.put("y", singleData[4]);
lineArrayData.put(lineCounter, map);
lineCounter++;
}
System.out.println(lineArrayData);
I have input
barcode||testowy test||1||100||100
text||texttstdasd||2||500||300
and my output is:
{0={text=texttstdasd, page=2, type=text, y=300, x=500}, 1={text=texttstdasd, page=2, type=text, y=300, x=500}}
what have I done wrong?

Move the following line inside the loop:
HashMap<String, String> map = new HashMap<String, String>();
Otherwise every iteration modifies the same inner map. The end result is that the outer map contains multiple references to the same inner map.
Here is the corrected version:
for ( String line : this.lines )
{
HashMap<String, String> map = new HashMap<String, String>();
singleData = line.split("\\|\\|");
...

Declare HashMap<String, String> map = new HashMap<String, String>(); inside the for loop.

You are using the same instance of the map in the loop. Also that should be
Map<Integer, Map<String, String>> lineArrayData = new HashMap<Integer, HashMap<String, String>>();
Map<String, String> map = new HashMap<String, String>();

Related

Add first element of Map into another list at 1st Position and so on...second map element into second position of list

**Here We have product bean. There is some attributes like productname,tax and ..etc. **
Product product = new Product();
product.setProductName("Laptop");
Product product1 = new Product();
product1.setProductName("Mobile");
List<Product> productList = Arrays.asList(product, product1);
**Created Map of Map<String, List<Map<String, String>>>**
Map<String, List<Map<String, String>>> productCart = new HashMap<String, List<Map<String, String>>>();
List<Map<String, String>> listTax1 = new ArrayList<Map<String, String>>();
List<Map<String, String>> listTax2 = new ArrayList<Map<String, String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("XR", "123");
map1.put("TAX", "234");
map1.put("SURCHARGE", "567");
listTax1.add(map1);
Map<String, String> map2 = new HashMap<String, String>();
map2.put("XR", "1234");
map2.put("TAX", "2345");
map2.put("SURCHARGE", "5678");
listTax2.add(map2);
productCart.put("1", listTax1);
productCart.put("2", listTax2);
//
I want to add productCart into productList one by one.//
Add first element of Map into another list at 1st Position and so on...second map element into second position of list.
Try with Java 8
Yes you can use this one -
int j=0;
for(int i=0;i<productList.size();i++) {
Product productData= productList.get(i);
List keys =new ArrayList(productCart.keySet());
while(j<=i) {
Object listKeys= keys.get(i);
List<Map<String, String>> pro=productCart.get(listKeys);
for (Map<String, String> map : pro) {
map.forEach((k,v)-> {
//Write Yours Conditions
if(k.equalsIgnoreCase("SURCHARGE")){
}
});
}
j++;
}
}

Java append `HashMap` values to existing HashMap if key matches

I have below HashMap(to.String()) printed below.
HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();
HashMap abc = {disabled={account={testConfiguration=1, iterate=1}}}
I want to append {group={iterate=1}} to existing map if key disabled matches.
Finally my map should look like below, how can I achieve it?
HashMap abc = {disabled={account={testConfiguration=1, iterate=1}, {group={iterate=1}}}
I think you want this:
abc.computeIfPresent("disabled", (k,v) -> {
v.put("group", yourValue);
return v;
});
or simply:
if (abc.containsKey("disabled")) {
abc.get("disabled").put("group", yourValue);
}
I personally prefer the first approach, since it's a bit faster and works properly with concurrent maps.
Here is the example for your desired output
disabled={account={testConfiguration=1, iterate=1}, group={iterate=1}}
HashMap<String, Integer> accountmap = new HashMap<>();
HashMap<String, Integer> groupMap = new HashMap<>();
HashMap<String, HashMap<String, Integer>> disableMap = new HashMap<>();
HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();
accountmap.put("testConfiguration",1);
accountmap.put("iterate",1);
disableMap.put("account",accountmap);
abc.put("disabled", disableMap);
if(abc.containsKey("disabled")){
groupMap.put("iterate", 1);
disableMap.put("group",groupMap);
}
System.out.println(abc.entrySet());
The below code gives you the hashmap in the following format
{disabled={account={testConfiguration=1, iterate=1}, group={iterate=1}}}
public static void main(String []args) {
HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();
// HashMap abc = {disabled={account={testConfiguration=1, iterate=1}}}
HashMap<String, Integer> thirdHash = new HashMap<>();
thirdHash.put("testConfiguration", 1);
thirdHash.put("iterate", 1);
HashMap<String, HashMap<String, Integer>> secondHash = new HashMap<>();
secondHash.put("account", thirdHash);
abc.put("disabled", secondHash);
// append {group={iterate=1}}
HashMap<String, Integer> appendFirst = new HashMap();
appendFirst.put("iterate", 1);
if (abc.containsKey("disabled")) {
abc.get("disabled").put("group", appendFirst);
}
System.out.println(abc);
}
Happy Coding.

Problems building hashmap java

I'm in a little trouble building a hashmap but it took me a lot of time and I don't have a lot of experience with this kind of objects, my problem is when building the next hashmap:
Map<String, Map<String, Map<String, Object>>> map = new HashMap<String, Map<String, Map<String, Object>>>();
Map<String, Map<String, Object>> map1 = new HashMap<String, Map<String, Object>>();
Map<String, Object> map2 = new HashMap<String, Object>();
Map<String, Object> map3 = new HashMap<String, Object>();
map2.put("one",1);
map1.put("two", map2);
map.put("cero", map1);
System.out.println(map);
The output is:
{cero={two={one=1}}}
But now I want to add another key percent with string value 10 at cero key level like:
{percent=10,cero={two={one=1}}}
I tried something like:
Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("percent", "10");
map.get("cero").putAll(map3);
There is an error in putAll method 'cause java needs a Map<String, Map<String, Object>> kind of object but I only need to add that percent property. Hope I'm clear with my question and you guys can help me, thanks.
We can try to add map1 to map3
Map<String, Map<String, Map<String, Object>>> map = new HashMap<String,
Map<String, Map<String, Object>>>();
Map<String, Map<String, Object>> map1 = new HashMap<String, Map<String, Object>>
();
Map<String, Object> map2 = new HashMap<String, Object>();
Map<String, Object> map3 = new HashMap<String, Object>();
map2.put("one",1);
map1.put("two", map2);
map3.put("percent", "10");
map3.put("cero",map1);
System.out.println(map3);
This gives following structure in map3
{percent=10,cero={two={one=1}}}

how do i write this as a list<map<string, string> structure in java

how do i write this as a list structure in java
In this case i want the structure to be like this, Where options is also a key in another
hashmap called styles
options[{"value":"0","label":"zero"},{"value":"1","label":"one"},
{"value":"2","label":"two"}]
Here if i want to access options[1].value should give me 1 and options[2].label should give me two.
How can i achieve this with
LIst<Map<string><string[]>>?
Also Can i pass "options" array as one of the keys in my hash map
protected Map<String, String[]> getValueProperties(int view, Field field) {
Map<String, String> properties = new HashMap<String,String[]>();
properties.put("options", []);
return properties
}
I am new to handling data in this format, any pointers will be good
I think this can do:
List<Map<String,String>> options = new ArrayList<Map<String,String>>();
and populate as :
Map<String, String> option1 = new HashMap<String, String>();
option1.put("value", "0");
option1.put("level", "zero");
options.add(option1);
Map<String, String> option2 = new HashMap<String, String>();
option2.put("value", "1");
option2.put("level", "one");
options.add(option2);
Map<String, String> option3 = new HashMap<String, String>();
option3.put("value", "2");
option3.put("level", "two");
options.add(option3);
EDIT: You can populate the list in a loop as below:
List<Map<String,String>> options = new ArrayList<Map<String,String>>();
String[] levels = {"zero", "one", "two"};
for(int indx = 0; indx <levels.length; indx++){
Map<String, String> option = new HashMap<String, String>();
option.put("value", String.valueOf(indx));
option.put("level", levels[indx]);
options.add(option);
}
Use this data structure:
List< Map<String, String> >

Search a HashMap in an ArrayList of HashMap

I have an ArrayList of HashMap. I want to search a HashMap in it but unable to find a way to achieve this. Please suggest me how it can be done?
Thanks.
Answer to your question the way i understood it!
for (HashMap<String, String> hashMap : yourArrayList)
{
// For each hashmap, iterate over it
for (Map.Entry<String, String> entry : hashMap.entrySet())
{
// Do something with your entrySet, for example get the key.
String sListName = entry.getKey();
}
}
Your Hashmap might use other types, this one uses Strings.
See if this helps:
#Test
public void searchMap() {
List<Map<String, String>> listOfMaps = new ArrayList<Map<String,String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
Map<String, String> map2 = new HashMap<String, String>();
map1.put("key2", "value2");
Map<String, String> map3 = new HashMap<String, String>();
map1.put("key3", "value3");
listOfMaps.add(map1);
listOfMaps.add(map2);
listOfMaps.add(map3);
String keyToSearch = "key2";
for (Map<String, String> map : listOfMaps) {
for (String key : map.keySet()) {
if (keyToSearch.equals(key)) {
System.out.println("Found : " + key + " / value : " + map.get(key));
}
}
}
}
Cheers!
Object myObj;
Object myKey;
//Traverse the list
for(HashMap curMap : listOfMaps){
//If this map has the object, that is the key doesn't return a null object
if( (myObj = curMap.get(myKey)) != null) {
//Stop traversing because we are done
break;
}
}
//Act on the object
if(myObj != null) {
//TODO: Do your logic here
}
If you are looking to get the reference to the Map instead of the object (for whatever reason) same process applies, except you just store the reference to the map:
Map myMap;
Object myKey;
//Traverse the list
for(HashMap curMap : listOfMaps){
//If this map has the object, that is the key doesn't return a null object
if(curMap.get(myKey) != null) {
//Store instance to the map
myMap = curMap;
//Stop traversing because we are done
break;
}
}
//Act on the map
if(myMap != null) {
//TODO: Do your logic here
}
Try below improved code for searching the key in a list of HashMap.
public static boolean searchInMap(String keyToSearch)
{
boolean returnVal = false;
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
Map<String, String> map2 = new HashMap<String, String>();
map1.put("key2", "value2");
Map<String, String> map3 = new HashMap<String, String>();
map1.put("key3", "value3");
listOfMaps.add(map1);
listOfMaps.add(map2);
listOfMaps.add(map3);
for (Map<String, String> map : listOfMaps)
{
if(map.containsKey(keyToSearch))
{
returnVal =true;
break;
}
}
return returnVal;
}
The Efficient way i've used to search a hashmap in an arraylist without using loops. Since loop makes execution time longer
try{
int index = list.indexOf(map); // map is your map to find in ArrayList
if(index>=0){
HashMap<String, String> map = array_list.get(index);
// Here you can get your values
}
}
catch(Exception e){
e.printStackTrace();
Log.i("HashMap","Not Found");
}
if you have an ArrayList like this one: ArrayList<HashMap<String, String>>
and you want to compare one of the values inside the HashMap try this code.
I use it to compare settings of my alarm notifications.
for (HashMap<String, String> map : AlarmList) {
for (String key : map.keySet())
{
if (key.equals("SendungsID"))
{
if(map.get(key).equals(alarmMap.get("AlarmID")))
{
//found this value in ArrayList
}
}
}
}

Categories