Sum, Mean, Median and Standard Deviation Using Lists in Java

Well, I needed methods for sum, mean, median, and standard deviation in Java using Lists, so I coded them. Probably is not the most beautiful code that you've ever seen but it works.
import java.util.*;
class methods {
    public int sum (List<Integer> a){
        if (a.size() > 0) {
            int sum = 0;

            for (Integer i : a) {
                sum += i;
            }
            return sum;
        }
        return 0;
    }
    public double mean (List<Integer> a){
        int sum = sum(a);
        double mean = 0;
        mean = sum / (a.size() * 1.0);
        return mean;
    }
    public double median (List<Integer> a){
        int middle = a.size()/2;

        if (a.size() % 2 == 1) {
            return a.get(middle);
        } else {
           return (a.get(middle-1) + a.get(middle)) / 2.0;
        }
    }
    public double sd (List<Integer> a){
        int sum = 0;
        double mean = mean(a);

        for (Integer i : a)
            sum += Math.pow((i - mean), 2);
        return Math.sqrt( sum / ( a.size() - 1 ) ); // sample
    }
}
class t {
    public static void main (String[]args) {

        methods m = new methods();

        List<Integer> c = Arrays.asList(2,49,11,44,88,1,1,5,33,88,5,44,2,44,44,132,6,2,22,22,5,1,22,22);
        Collections.sort(c);

        System.out.println(m.median(c));
        System.out.println(m.mean(c));
        System.out.println(m.sd(c));
    }
}

Remove if(debug) intructions from Java bytecode with a static flag

One of the several techniques (a MacGyver style) for debug in Java is insert if(DEBUG) messages for monitoring errors and events. However, according to the size of your code, the number of conditional tests performed to check if the DEBUG flag was enabled can affect the performance of your application.

In C one of the alternatives is to use #define DEBUG directive jointly with #ifdef DEBUG tests, hence, according to this flag, compiler will inserts or not the debug code in the executable.

In Java you can do that using a static flag, for instance, considers the example as follows:

class Teste{

        public static final boolean DEBUG = true;

        public static void main( String[] args ){

                if( DEBUG ){
                        int a = 10;
                        System.out.println( "a = " + a );
                }
        }
}

Compiling the code:

$ javac Teste.java

Verifying the generated bytecode to check the if(debug) instructions:

$ javap -c Teste.java

Compiled from "Teste.java"
class Teste extends java.lang.Object{
public static final boolean DEBUG;

Teste();
  Code:
   0:    aload_0
   1:    invokespecial    #1; //Method java/lang/Object."":()V
   4:    return

public static void main(java.lang.String[]);
  Code:
   0:    bipush    10
   2:    istore_1
   3:    getstatic    #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   6:    new    #3; //class java/lang/StringBuilder
   9:    dup
   10:    invokespecial    #4; //Method java/lang/StringBuilder."":()V
   13:    ldc    #5; //String a =
   15:    invokevirtual    #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   18:    iload_1
   19:    invokevirtual    #7; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
   22:    invokevirtual    #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   25:    invokevirtual    #9; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   28:    return

}

Changing the debug flag to false:

class Teste{

        public static final boolean DEBUG = false;

        public static void main( String[] args ){

                if( DEBUG ){
                        int a = 10;
                        System.out.println( "a = " + a );
                }
        }
}

Recompiling the code:

$ javac Teste.java

Verifying again the generated bytecode we can see that compiler take in account that since the debug flag is constant (final) its value cannot be changed during the execution so the conditional test will always returns false and can be removed.

$ javap -c Teste.java

Compiled from "Teste.java"
class Teste extends java.lang.Object{
public static final boolean DEBUG;

Teste();
  Code:
   0:    aload_0
   1:    invokespecial    #1; //Method java/lang/Object."":()V
   4:    return

public static void main(java.lang.String[]);
  Code:
   0:    return

}

See ya

Ant Compile With rJava library

This is pretty simple but for the sake of “I-will-not-forget-it-anymore” I will write it here. I copied some files of a Java project to a new machine. When I tried to execute it in the new place, “Exception in thread “main” java.lang.UnsupportedClassVersionError: Bad version number in .classa file”. Recompiling everything should make it work. Since my code requires rJava it is necessary to inform this to the ant (I’m using ant by the way).  The command which made my day is:

ant clean compile -lib ~/R/i486-pc-linux-gnu-library/2.9/rJava/jri/JRI.jar

2.9: be aware about the version you’ve installed, if you’ve compiled the packages in a version < 2.10, you will need to reinstall ’em. In my case I did reinstall nlme, mgcv, spatstat, and igraph.

cannot mkdir R_TempDir (não é possível criar um diretório em R_TempDir)

I’m constantly using rJava/JRI for a large amount of simulations. Repently it was not working anymore, and since I’d not change anything in the main code, it was a quite weird behavior. My rJava binding looks like this and the first line was the only being executed:

System.out.println("Creating Rengine (with arguments)");
re = new Rengine(args.split(" "), false, null);
if (!re.waitForR()) {
System.out.println("Cannot load R");
return;
}
System.out.println("R loaded");

That was awkward so I tried to use R in the console. When I execute the “R” command I received “cannot mkdir R_TempDir”. So I dug into the R source code to know when it happens. So I figured out that R tries to read environment variables TMPDIR, TMP, and TEMP before set “/tmp” as default one. Since this variables were not set, the “/tmp” is the destiny of the temporary stuff.

When I saw my “/tmp” directory was full, I mean, filled with the maximum number of directories possible in an Ext3 File System, 32K. I realized that all the problem was that R was not getting space for the new “Rtmp…” directories.

To solve that, “rmdir Rtmp*” inside “/tmp” dir. And the world is a happy place again.

Multi-dimensional array in Java

Since Java does not have pointers I was thinking if it can hold multi-dimensional arrays. Multi-dimensional array is an array where each row is another array, which can have different sizes. In C you can create an array of pointers and allocates each one to an array of different sizes. The following are two examples to allocates a multi-dimensional array in Java:

// declaration statement
int tri[][] = { {1,2,3}, {4,5}, {1} };

// dinamically statement
int[][] tri;
tri = new int[10][];
for (int r=0; r<tri.length; r++) {
	tri[r] = new int[r+1];
}
 
// print the triangle matrice
for (int r=0; r<tri.length; r++) {
	for (int c=0; c<tri[r].length; c++) {
		System.out.print(" " + tri[r][c]);
	}
	System.out.println("");
}

Read more:
http://www.go4expert.com/forums/showthread.php?t=1162

See ya