Because I am constantly busy working on something, I have never had time to actually put everything in words and pictures. But, since you got here, then you must have already seen some part of my work - and this is the way I’m talking. I'm 24, born in Romania, studied at UPG Romania in software development field. I started from 0, mostly with basic stuff, and I’m evolving every day to an expert. I'm focused on freelancing projects, from small websites, to really heavy stuff.

Friday, September 23, 2011

How to measure the time of a process


To measure the time of a process just call the System.nanoTime method when process starts and again when process ends. The time of the process will be the diference betwen the two calls.

package time;

public class Time {

public static void main(String[] args) {

long start_time, end_time, elapsedTime;

start_time = System.nanoTime();

// ... the code being measured ...

end_time = System.nanoTime();
elapsedTime = end_time - start_time;

System.out.println("Start: " + start_time);
System.out.println("End : " + end_time);
...

The System.nanoTime method returns values in nanoseconds, to convert nanoseconds to miliseconds or seconds you just need to make a few divisions:

System.out.println("The process took approximately:\n "
+elapsedTime+" nano seconds\n "
+(elapsedTime/1000000.0)+" miliseconds\n "
+(elapsedTime/1000000000.0)+" seconds");
This tip can be found at: http://download.oracle.com/javase/7/docs/api/

Removing entries from a HashMap


There are a few solutions for looping a HashMap, but one of the most elegant looks like below:

HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
map.put("Four", 4);
map.put("Five", 5);
map.put("Six", 6);
map.put("Seven", 7);
map.put("Eight", 8);
map.put("Nine", 9);
map.put("Ten", 10);

for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(map.getKey() + " " + map.getValue());
}

Now, that is great, but if you try to remove an entry while looping

for (Map.Entry<String, Integer> entry : map.entrySet()) {
if(entry.getValue() > 5){
map.remove(entry.getKey());
}
}

an java.util.ConcurrentModificationException will occur!
Solving this issue involves adding an Iterator which conforming to documentation “Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.” will allows us to call remove(). Therefore, here it is:

for(Iterator<Map.Entry<String,Integer>>it=map.entrySet().iterator();it.hasNext();){
Map.Entry<String, Integer> entry = it.next();
if (entry.getValue() > 5) {
it.remove();
}
}
Done !