I am trying to implement the use of two HashMaps and it seems to be more or less successful also.But now my problem is i want to update the value of a hashMap based on a check.ie if userId is already existing in the hash i need to update the timestamp corresponding to it...
Below given is my code.How can we accomplish the updation of values .Can that be done usiong setValue..?but how..?please help me friends..
public static void main(String[] args)
{
HashMap sessionTimeStampHash = new HashMap<Long, Long>(); //sessionID is the key and timeStamp is the value
//userID is the key and sessionTimeStampHash object is the value
HashMap<String, HashMap<Long, Long>> userSessionHash = new HashMap<String, HashMap<Long, Long>>();
sessionTimeStampHash.put("sessionID", "timeStamp");
userSessionHash.put("userID", sessionTimeStampHash);
// System.out.println(userSessionHash);
sessionTimeStampHash = new HashMap();
sessionTimeStampHash.put("sessionID1", "timeStamp1");
userSessionHash.put("userID1", sessionTimeStampHash);
// System.out.println(userSessionHash);
sessionTimeStampHash = new HashMap();
sessionTimeStampHash.put("sessionID2", "timeStamp2");
userSessionHash.put("userID2", sessionTimeStampHash);
// System.out.println(userSessionHash);
sessionTimeStampHash = new HashMap();
sessionTimeStampHash.put("sessionID3", "timeStamp3");
userSessionHash.put("userID3", sessionTimeStampHash);
// System.out.println(userSessionHash);
for (Entry<String, HashMap<Long, Long>> entry : userSessionHash.entrySet())
{
String key = entry.getKey();
System.out.println(key);
System.out.println(entry.getValue());
String userId = "userID3";
if (key.equals(userId))
{
System.out.println("Check Successful");
String TimeStamp = newTime;
entry.setValue() // how can i change my timeStamp
}
}
}
You can do without for loop
if(userSessionHash.get(userId)!=null)
userSessionHash.get(userId).put(userSessionHash.get(userId).keySet().toArray[0], timestamp);
Loop on your second map (I assume you want to update all the sessionIds for the user) and modify the value.
if (key.equals(userId))
{
System.out.println("Check Successful");
String TimeStamp=newTime;
for ( String sessionId : entry.getValue().keySet() )
{
entry.put(sessionid, timeStamp);
}
}
String userId = "userID3";
Long timeStamp = userSessionHash.containsKey(userId) ? userSessionHash.get(userSessionHash) : 0;
userSessionHash.put(userId,new AtomicLong(request.getSession(false).getMaxInactiveInterval()))
Related
I set list on another class
List<DataModel> dataList = new ArrayList<DataModel>();
parsed on class
for(DataModel list : dataList) {
final String[] data = {list.getVar_a(), list.getVar_b()};
System.out.println("out data");
System.out.println(list.getVar_a());
System.out.println(list.getVar_b());
}
this prints data
out data
val_a
val_b
Model Class
class DataModel {
private String var_a, var_b;
//Getter & Setter
}
But now, I use and set map on another class and I'm not implementing a model class because in real case it has too many variables.
Map<String, Object> mapData = new LinkedHashMap<String, Object>();
when I set data on map, its result from database
Map<String, Object> map = new LinkedHashMap<String, Object>();
msg = (String) cs.getObject(5);
rs = (ResultSet) cs.getObject(4);
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
if(rs.next()){
int jml = 0;
do {
Map<String, Object> data = new LinkedHashMap<>();
for (int i = 1; i <= count; i++ ) {
String name = rsmd.getColumnName(i);
data.put(name, rs.getObject(name));
}
map.put(""+jml, data);
jml++;
} while(rs.next());
setStatus(SUCCESS);
setMessage(msg);
} else {
LOG.info(NO_DATA_FOUND);
}
parsed on class
for(Map.Entry<String,Object> list : mapData.entrySet()) {
String key = list.getKey();
Object val = list.getValue();
System.out.println("out data");
System.out.println(key);
System.out.println(val);
}
this prints data
out data
0
{var_a=val_a, var_b=val_b}
I want to get value on object like this
out data
val_a
val_b
Change your Map for loop to:
for(Map.Entry<String,Object> list : mapData.entrySet()) {
DataModel value = (DataModel) list.getValue();
System.out.println("out data");
System.out.println(value.getVar_a());
System.out.println(value.getVar_b());
}
First you have a map of object, and what you really need is a Map of Map.
Here is your reading a map of object.
for(Map.Entry<String,Object> list : mapData.entrySet()) {
String key = list.getKey();
Object val = list.getValue();
System.out.println("out data");
System.out.println(key);
System.out.println(val);
}
What you really need is a map of map as I am showing below.
Map<String, Map<String, Object>> map = new LinkedHashMap<String, Map<String, Object>>()
Now if you read it as map of map, You can have the result that you need.
0 : {a1:v1, a2:v2, etc...},
1 : {a2:v2, a2:v2, etc...},
2 : {a3:v3, a3:v3, etc...}
for(Map.Entry<String,Map<String, Object> list : mapData.entrySet()) {
String key = list.getKey();
System.out.println("out data");
for(Map.Entry<String,Object> innermap : list.getValue().entrySet()) {
//System.out.println(innermap.getKey());
System.out.println(innermap.getValue());
}
}
TreeMap<String, HashMap<String, String>> myData = new TreeMap<>();
HashMap<String, String> data = new HashMap<>(); //data present in this map will be name as key & Values will rest other details
HashMap<String, String> lock = new HashMap<>(); //data present in this map Will be id as Key & Values will be name+Email
Iterator itr = lock.entrySet().iterator();
Iterator trans = data.entrySet().iterator();
HashMap<String, String> vessel = new HashMap<>(); //Temp Holding of EachKey & value of name as key and rest as values
TreeMap demo=new TreeMap();
while (itr.hasNext()) {
Entry e = (Entry) itr.next();
String key = (String) e.getKey();
name = ReadExcel.getString((String) e.getValue(), 0);
String email = ReadExcel.getString((String) e.getValue(), 1);
while (trans.hasNext()) {
vessel.clear();
Entry ex = (Entry) trans.next();
String NameVs = (String) ex.getKey();
String emailVs = ReadExcel.getString((String) ex.getValue(), 0);
if (name.equalsIgnoreCase(NameVs) && email.equalsIgnoreCase(emailVs)) {
vessel.put(NameVs, data.get(NameVs));
//System.err.println(vessel.values());
myData.put(key, vessel); //Putting data in treeMap
System.out.println(myData.entrySet());
break;
}
}
trans = data.entrySet().iterator();
}
Need output as
[1={RAM=aa#gmail.com Domulur 7894561230 }, 2={ANIL=xyZ#gmail.com MUM 8464648848 }] . If i have some data as "ID Name Email Address Mob". But the problem is if i use clear() data is replaced by last row data .For, Ex: [1={ANIL=xyZ#gmail.com MUM 8464648848 }, 2={ANIL=xyZ#gmail.com MUM 8464648848 }] and if i don't use clear(), values are appending. For ex, [1={RAM=aa#gmail.com Domulur 7894561230,ANIL=xyZ#gmail.com MUM 8464648848 }, 2={RAM=aa#gmail.com Domulur 7894561230,ANIL=xyZ#gmail.com MUM 8464648848 }].
Need Help Thanks.
You use the same HashMap<String, String> instance as value for all the keys of your TreeMap, so of course all the keys will have the same value.
You should create a new HashMap for each key:
....
while (itr.hasNext()) {
Entry e = (Entry) itr.next();
String key = (String) e.getKey();
name = ReadExcel.getString((String) e.getValue(), 0);
String email = ReadExcel.getString((String) e.getValue(), 1);
while (trans.hasNext()) {
HashMap<String, String> vessel = new HashMap<>();
Entry ex = (Entry) trans.next();
String NameVs = (String) ex.getKey();
String emailVs = ReadExcel.getString((String) ex.getValue(), 0);
if (name.equalsIgnoreCase(NameVs) && email.equalsIgnoreCase(emailVs)) {
vessel.put(NameVs, data.get(NameVs));
myData.put(key, vessel); //Putting data in treeMap
break;
}
}
trans = data.entrySet().iterator();
}
....
I have a set of strings like this
A_2007-04, A_2007-09, A_Agent, A_Daily, A_Execute, A_Exec, B_Action, B_HealthCheck
I want output as:
Key = A, Value = [2007-04,2007-09,Agent,Execute,Exec]
Key = B, Value = [Action,HealthCheck]
I'm using HashMap to do this
pckg:{A,B}
count:total no of strings
reports:set of strings
Logic I used is nested loop:
for (String l : reports[i]) {
for (String r : pckg) {
String[] g = l.split("_");
if (g[0].equalsIgnoreCase(r)) {
report.add(g[1]);
dirFiles.put(g[0], report);
} else {
break;
}
}
}
I'm getting output as
Key = A, Value = [2007-04,2007-09,Agent,Execute,Exec]
How to get second key?
Can someone suggest logic for this?
Assuming that you use Java 8, it can be done using computeIfAbsent to initialize the List of values when it is a new key as next:
List<String> tokens = Arrays.asList(
"A_2007-04", "A_2007-09", "A_Agent", "A_Daily", "A_Execute",
"A_Exec", "P_Action", "P_HealthCheck"
);
Map<String, List<String>> map = new HashMap<>();
for (String token : tokens) {
String[] g = token.split("_");
map.computeIfAbsent(g[0], key -> new ArrayList<>()).add(g[1]);
}
In terms of raw code this should do what I think you are trying to achieve:
// Create a collection of String any way you like, but for testing
// I've simply split a flat string into an array.
String flatString = "A_2007-04,A_2007-09,A_Agent,A_Daily,A_Execute,A_Exec,"
+ "P_Action,P_HealthCheck";
String[] reports = flatString.split(",");
Map<String, List<String>> mapFromReportKeyToValues = new HashMap<>();
for (String report : reports) {
int underscoreIndex = report.indexOf("_");
String key = report.substring(0, underscoreIndex);
String newValue = report.substring(underscoreIndex + 1);
List<String> existingValues = mapFromReportKeyToValues.get(key);
if (existingValues == null) {
// This key hasn't been seen before, so create a new list
// to contain values which belong under this key.
existingValues = new ArrayList<>();
mapFromReportKeyToValues.put(key, existingValues);
}
existingValues.add(newValue);
}
System.out.println("Generated map:\n" + mapFromReportKeyToValues);
Though I recommend tidying it up and organising it into a method or methods as fits your project code.
Doing this with Map<String, ArrayList<String>> will be another good approach I think:
String reports[] = {"A_2007-04", "A_2007-09", "A_Agent", "A_Daily",
"A_Execute", "A_Exec", "P_Action", "P_HealthCheck"};
Map<String, ArrayList<String>> map = new HashMap<>();
for (String rep : reports) {
String s[] = rep.split("_");
String prefix = s[0], suffix = s[1];
ArrayList<String> list = new ArrayList<>();
if (map.containsKey(prefix)) {
list = map.get(prefix);
}
list.add(suffix);
map.put(prefix, list);
}
// Print
for (Map.Entry<String, ArrayList<String>> entry : map.entrySet()) {
String key = entry.getKey();
ArrayList<String> valueList = entry.getValue();
System.out.println(key + " " + valueList);
}
for (String l : reports[i]) {
String[] g = l.split("_");
for (String r : pckg) {
if (g[0].equalsIgnoreCase(r)) {
report = dirFiles.get(g[0]);
if(report == null){ report = new ArrayList<String>(); } //create new report
report.add(g[1]);
dirFiles.put(g[0], report);
}
}
}
Removed the else part of the if condition. You are using break there which exits the inner loop and you never get to evaluate the keys beyond first key.
Added checking for existing values. As suggested by Orin2005.
Also I have moved the statement String[] g = l.split("_"); outside inner loop so that it doesn't get executed multiple times.
i want to retrieve all data that are present in my data structure, which is of type Map of Maps.The data structure is mentioned below.
public static Map<String, Map<String, String>> hourlyMap = new HashMap<String, Map<String, String>>();
i need all the data that are stored in the map irrespective of key.
This may help you
Map<String,Map<String,String>> hourlyMap = new HashMap<String,Map<String,String>>();
for(Map<String,String> i:hourlyMap.values()){
// now i is a Map<String,String>
for(String str:i.values()){
// now str is a value of map i
System.out.println(str);
}
}
Try:
Set<String> allData = new HashSet<>(); // will contain all the values
for(Map<String, String> map : hourlyMap.values()) {
allData.addAll(map.values());
}
for (String outerKey: hourlyMap.keySet()) {
// outerKey holds the Key of the outer map
// the value will be the inner map - hourlyMap.get(outerKey)
System.out.println("Outer key: " + outerKey);
for (String innerKey: hourlyMap.get(outerKey).keySet()) {
// innerKey holds the Key of the inner map
System.out.println("Inner key: " + innerKey);
System.out.println("Inner value:" + hourlyMap.get(outerKey).get(innerKey));
}
}
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
}
}
}
}