Facing an issue with hashtable - java

I am facing an issue with hashtable. I am working with blackberry. In the below code the sysout "vector size info is" shows the data has two but the sysout "size in hashtable" shows the data has one. I do not understand this.
try {
Hashtable listUserEvents = getUserInfo();
Vector listEvents = new Vector();
EventList eventList = (EventList) PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_ONLY);
Enumeration events = eventList.items();
while (events.hasMoreElements()) {
System.out.println("in while");
Event event = (Event) events.nextElement();
if (eventList.isSupportedField(Event.START) && event.countValues(Event.START) > 0) {
long start = event.getDate(Event.START, 0);
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
String dateString = sdf.formatLocal(start);
SimpleDateFormat sdf1 = new SimpleDateFormat("MMM dd,yyyy");
String date = sdf1.formatLocal(start);
System.out.println("dates are :" +date+ "user" +usrDate);
if (usrDate.equalsIgnoreCase(date)) {
System.out.println("dates are equal:" +date);
EventsBean eventBean = new EventsBean();
if (eventList.isSupportedField(Event.END) && event.countValues(Event.END) > 0) {
long end = event.getDate(Event.END, 0);
SimpleDateFormat sdform = new SimpleDateFormat("MMM dd, yyyy HH:mm");
String dateString1 = sdform.formatLocal(end);
eventBean.setStartDate(dateString);
eventBean.setEndDate(dateString1);
}
listEvents.addElement(eventBean);
if (listUserEvents.containsKey(usrDate)) {
Vector info = (Vector) listUserEvents.get(usrDate);
System.out.println("the size in getEvents is" + info.size());
info.addElement(eventBean);
System.out.println("vector size info is" + info.size());
listUserEvents.put(usrDate, info);
} else {
listUserEvents.put(usrDate, listEvents);
}
}
}
}
System.out.println("size in hashtable "+listUserEvents.size());
Now if i loop over this hashtable using the below code i get the data in vector has one
Enumeration events = listEvent.keys();
while (events.hasMoreElements()) {
String key = (String) events.nextElement();
if (key.equals(label1.getText())) {
Vector object = (Vector) listEvent.get(key);
System.out.println("vector size"+object.size());
Enumeration hashtable = listEvent.keys();
while (hashtable.hasMoreElements()) {
String keys = (String) hashtable.nextElement();
if (keys.equals(label1.getText())) {
Vector data = (Vector) listEvent.get(keys);
the data here gives only one ,but above it shows two.

The size of your hashtable is one, because it only has one entry.
The size of your vector that you store in the hashtable will not be reflected in the size of the hashtable.

There is only one item in Hashtable because you have only inserted one item - a list with two elements.

Related

Why after split line into an array, the code after for-loop doesn't work?

In this cycle, the string within an arraylist is divided, and each word is inserted into an array. I only need the date that is in second position to compare it with a date that I pass. If it is not present, the entire string is deleted from the arraylist.
For this reason I use an iterator. Everything works but the code after the for loop doesn't work. Eliminating the insertion of words in the array works everything. I used the same method elsewhere and it works without problems, I don't understand.
CreateMap(ArrayList<String> eventi,String data) throws ParseException {
list_eventi = eventi;
intervallo = data;
String [] periodo;
String[] arrayData;
periodo = intervallo.split("-");
String data_in = periodo[0];
String data_fin = periodo[1];
SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy");
Date dateIn = format.parse(data_in);
Date dateFin = format.parse(data_fin);
String[] line;
for (Iterator<String> iter = eventi.listIterator(); iter.hasNext(); ) {
String a = iter.next();
line = a.split(" "); //this is the problem//
String d = line[2];
Date dateImport = format.parse(d);
if(!dateImport.before(dateIn) && !dateImport.after(dateFin)) {
//date che sono nell'intervallo
// date between
System.out.println(d);
} else{
System.out.println("dati da eliminare " + a);
//iter.remove();
}
}
------------------------------ after this line the code doesn't execute
System.out.println("dati rimanenti");
System.out.println(list_eventi.toString());
//Map_for_login(eventi);
//Map_for_all(eventi);
There is no error message after executing the code, but after the for loop there are other methods and various system.out but they don't work
Since your variable eventi is an ArrayList you can just use the .forEach() method.
Fix:
List<String> resEventi = new ArrayList(); // the resulting eventi arrayList with only the correct values
eventi.forEach( a -> {
line = a.split(" ");
String d = line[2];
Date dateImport = format.parse(d);
if(!dateImport.before(dateIn) && !dateImport.after(dateFin)) {
//date che sono nell'intervallo
// date between
resEventi.add(a);
System.out.println(d);
} else{
System.out.println("dati da eliminare " + a);
}
});
This should work given you pass in proper data (there may be an exception raised by format.parse(d)).

Sorting a map by date key in Java

I'm trying to sort a map in java by date key using TreeMap. Here's my code
public static void sort() {
BufferedReader br;
String line;
String[] data;
Date date ;
DateFormat df = new SimpleDateFormat("dd-mm-YYY");
Map<Date,String> map = new TreeMap<Date,String>();
try {
br = new BufferedReader(new FileReader(
"/home/user/Desktop/train/2013-training_set.txt"));
int i=0;
while ((line = br.readLine()) != null) {
++i;
data = line.split(":");
map.put(df.parse(data[1]), line);
}
System.out.println(map.size()+" i = "+i);
Set st = mp.entrySet();
Iterator it = st.iterator();
while (it.hasNext()) {
Map.Entry me = (Map.Entry) it.next();
System.out.print(me.getKey() + "->:");
System.out.println(me.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
The date[1] contains the date in string format and looks like (e.g. 21-3-2013). The problem is that it stores in the TreeMap(mp) only 12 key-value pairs(one for each month) instead of the 103(i) expected. Any ideas ?
See http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html.
Use y for year, M for month in year, and d for day in month. Specifically, lowercase m is minute in hour, while uppercase M is month in year.
It looks like the lines
data = line.split(":");
map.put(df.parse(data[1]), line);
Are effectively parsing out only the month. Line.split(":") is going to produce an array split by : . If you have dates formatted in your data file dd:mm:yyyy then the resulting array "data" should be {[dd], [mm], [yyyy]}. So data[1] is going to simply be the month.
I could be wrong, but I suspect this is why you are only getting the 12 key-value pairs; you are parsing only for the month, and any time you get a new month key, you're overwriting the old key.

Spring mongoDB map reduce key string

Im doing a map reduce in mongo as it follows:
List<Measurement> lista = new ArrayList<Measurement>();
String map = "function Map() {emit(this.emissionType,this.avgValue); }";
String reduce = "function Reduce (key, values) { var size = values.length; var result = (Array.sum(values))/size; return result; }";
Query query = new Query();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
Date date = cal.getTime();
query.addCriteria(Criteria.where("sensor.$id").is(sensorId).andOperator(Criteria.where("date").gt(date)));
MapReduceResults<Measurement> result = null;
try{
result = template.mapReduce(query,"measurements", map, reduce, Measurement.class);
}catch(Exception excep){
excep.printStackTrace();
}
Iterator itr = result.iterator();
while (itr.hasNext()) {
Object element = itr.next();
lista.add((Measurement) element);
}
What i want to do is to group by emissionType and get for each one its average value.
And with the reduce function I pretend to get the total average of all the averages.
Finally all the results i want to get must be of the last 24 hours.
The problem comes when I execute that and it doesnt return anything

How to parse two different objects from the same json file?

How to parse two different objects from the same json file knowing that parsing one of them block parsing the other, which means that i have to parse only one of them, this is my code:
try {
time = json1.getJSONObject(TAG_TIME);
String Time2 = time.toString();
deals = json1.getJSONObject(TAG_DEALS);
final String plusinfo = deals.getString(TAG_PLUS_INFO);
String title = deals.getString(TAG_TITLE);
Integer retail = deals.getInt(TAG_RETAIL);
String nretail = Integer.toString(retail);
Integer deal = deals.getInt(TAG_DEAL);
String ndeal = Integer.toString(deal);
String duration = deals.getString(TAG_DURATION);
String image = deals.getString(TAG_IMAGE_URL);
String participant = deals.getString(TAG_PARTICIPANT);
final String details = deals.getString(TAG_DETAILS);
final String name = deals.getString(TAG_ADVERTISER_NAME);
final String adress = deals.getString(TAG_ADVERTISER_ADDRESS);
final String phone = deals.getString(TAG_ADVERTISSER_PHONE);
/*String Time1 = deals.getString(TAG_DATE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = new GregorianCalendar(0,0,0).getTime();
Date date2 = new GregorianCalendar(0,0,0).getTime();
try {
date1 = sdf.parse(Time1);
date2 = sdf.parse(Time2);
} catch (ParseException e) {
e.printStackTrace();
}
final String precision = deals.getString(TAG_PRECISION);
JSONArray c = deals.getJSONArray(TAG_PRECISION);
ArrayList<String> arrays = new ArrayList<String>();
for(int i = 0; i < c.length(); i++){
precision = c.getString(i);
arrays.add(precision);
}
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_RETAIL, nretail);
map.put(TAG_DEAL, ndeal);
map.put(TAG_DURATION, duration);
map.put(TAG_IMAGE_URL, image);
map.put(TAG_PARTICIPANT, participant);
map.put(TAG_SERVER_TIME, Time2);
otherdeals.add(map);
What do you mean it gets blocked? I dont see what the issue is with what you have posted. If you wish to parse two different JSON responses, either kick off two background threads (AsyncTask) or just parse them one after the other

adding Gregorian Calendar dates to an array and retrieving the date to print in a string

I am writing a credit card program. I want the program to use the current date every time the method is used to make a purchase and put the date into the array
private GregorianCalendar transDate;
public CreditCard(double amount,String storeName, GregorianCalendar transDate) {
this.amount=amount;
this.storeName=storeName;
transDate=new GregorianCalendar();
}
public void purchase(double amount, String storeName, GregorianCalendar date)throws Exception
{
if (numPurchases<purchases.length)
if (amount >0 )
if(amount+balance<=creditLimit)
if( GregorianCalendar.getInstance().getTimeInMillis()<=expDate.getTimeInMillis())
{
balance+=amount;
transDate=getTransDate();
purchases[numPurchases] = new CreditCard(amount, storeName,transDate);
numPurchases++;
}
else
{
throw new Exception("card expired");
}
else{
throw new Exception("insufficient credit");
}
else{
throw new Exception("invalid amount");
}
else{
throw new Exception("exceeded number of allowed purchases");
}
}
I would like to display the information in String info
info+="Purchases:\n";
for(int index=0;index<numPurchases;index++){
info+="["+(index+1)+"] ";
info+=transDate.get(Calendar.YEAR)+"\t";
info+= purchases[index].getStoreName()+"\t";
info+=(formatter.format(purchases[index].getPurchase()))+"\n" ;
}
how do I need to set up the code to use the current date and add it to the array and display it in the string
Why don't you use a List implementation instead of an array? You can override the toString method to print it the way you want.
final SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy");
List<Calendar> dates = new ArrayList<Calendar>() {
private static final long serialVersionUID = -5079502477457556887L;
#Override
public String toString() {
Iterator<Calendar> i = iterator();
if (!i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
Calendar c = i.next();
sb.append(formatter.format(c.getTime()));
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
};
dates.add(Calendar.getInstance());
dates.add(Calendar.getInstance());
System.out.println(dates);
What does your getTransDate() function do? Ideally it should return the transDate variable of CreditCard object. To calculate transDate for a purchase, you are better off renaming the method to calculateTransDate() or something like that.
Once you have getTransDate() method returning the transDate, your info string can be :
info+="Purchases:\n";
for(int index=0;index<numPurchases;index++){
info+="["+(index+1)+"] ";
info+=purchases[index].getTransDate().get(Calendar.YEAR)+"\t";
info+= purchases[index].getStoreName()+"\t";
info+=(formatter.format(purchases[index].getPurchase()))+"\n"
}

Categories