Reputation: 39
This below code checks id exist in ArrayList or not & then add it to map.
List<Map<Object, Object>> myListOfMaps = new ArrayList<Map<Object, Object>>();
ArrayList<String> al1 = new ArrayList<String>();
al1.add("92");
al1.add("94");
al1.add("91");
al1.add("98");
Map<Object,Object> map = new HashMap<Object,Object>();
ArrayList<String> result = new ArrayList<String>();
String id = "95,98,94";
for(int i=0;i<al1.size();i++)
{
if(id.contains(al1.get(i)))
{
result.add("true");
map.put("Access", true);
}
else
{
result.add("false");
map.put("Access", false);
}
myListOfMaps.add(map);
}
for (int i = 0 ; i < myListOfMaps.size() ; i++) {
Map<Object, Object> myMap = myListOfMaps.get(i);
for (Entry<Object, Object> entrySet : myMap.entrySet()) {
System.out.println("Key = " + entrySet.getKey() + " , Value = " + entrySet.getValue());
}
}
System.out.println(result);
Key = Access , Value = true
Key = Access , Value = true
Key = Access , Value = true
Key = Access , Value = true
[false, true, false, true]
arraylist result is fine but mapvalues returning true only.Please help me how to add k,v to map based on condition so that mapresult looks like this [{Access=false},{Access=true},{Access=false},{Access=true}].
Upvotes: 1
Views: 1018
Reputation: 202
This code will help you:
List<Map<String, Boolean>> myListOfMaps = new ArrayList<>();
List<String> al1 = new ArrayList<>();
al1.add("92");
al1.add("94");
al1.add("91");
al1.add("98");
String id = "95,98,94";
List<String> result = new ArrayList<>();
for (int i = 0; i < al1.size(); i++) {
Map<String, Boolean> map = new HashMap<>();
if (id.contains(al1.get(i))) {
result.add("true");
map.put("Access", true);
} else {
result.add("false");
map.put("Access", false);
}
myListOfMaps.add(map);
}
myListOfMaps.forEach(System.out::println);
System.out.println(result);
Upvotes: 0
Reputation: 1454
You ahve to declare a new Map every time in your loop
//...
al1.add("98");
//Map<Object,Object> map = new HashMap<Object,Object>();
ArrayList<String> result = new ArrayList<String>();
String id = "95,98,94";
for(int i=0;i<al1.size();i++)
{
Map<Object,Object> map = new HashMap<Object,Object>();
if(id.contains(al1.get(i)))
{
result.add("true");
map.put("Access", true);
}
else
{
result.add("false");
map.put("Access", false);
}
myListOfMaps.add(map);
}
//...
Upvotes: 0
Reputation: 910
A hashmap is a key-value data structure. The way you store items is based on the key.
This being said, if you add a key Access
to the map with the value false
and print the map it will show : Access: false
.
If you add again Access
with the value true
is not going to add a new key, is going to replace the previous value so it will print Access: true
So instead of adding the key Access
to the map, add the id. map.put(al1.get(i), true);
Upvotes: 1