How do I count the occurrences of a number in an array?

package org.kodejava.basic;

import java.util.HashMap;
import java.util.Map;

public class NumberOccurrenceInArray {
    public static void main(String[] args) {
        int[] numbers = new int[]{1, 8, 3, 4, 3, 2, 5, 7, 3, 1, 4, 5, 6, 4, 3};

        Map<Integer, Integer> map = new HashMap<>();
        for (int key : numbers) {
            if (map.containsKey(key)) {
                int occurrence = map.get(key);
                occurrence++;
                map.put(key, occurrence);
            } else {
                map.put(key, 1);
            }
        }

        for (Integer key : map.keySet()) {
            int occurrence = map.get(key);
            System.out.println(key + " occur " + occurrence + " time(s).");
        }
    }
}

The result are:

1 occur 2 time(s).
2 occur 1 time(s).
3 occur 4 time(s).
4 occur 3 time(s).
5 occur 2 time(s).
6 occur 1 time(s).
7 occur 1 time(s).
8 occur 1 time(s).

How do I use the double brace initialization?

The double brace initialization {{ ... }} is another way for initializing a collection objects in Java. It is offer a simple syntax for initializing a collection object.

package org.kodejava.lang;

import java.util.ArrayList;
import java.util.List;

public class DoubleBraceInitialization {
    public static void main(String[] args) {
        // Creates a list of colors and add three colors of
        // Red, Green and Blue.
        List<String> colors1 = new ArrayList<>();
        colors1.add("Red");
        colors1.add("Green");
        colors1.add("Blue");

        for (String color : colors1) {
            System.out.println("Color = " + color);
        }

        // Creates another list of colors and add three colors
        // using the double brace initialization.
        List<String> colors2 = new ArrayList<>() {{
            add("Red");
            add("Green");
            add("Blue");
        }};

        for (String color : colors2) {
            System.out.println("Color = " + color);
        }
    }
}

What’s actually happened is: the first brace creates an anonymous inner class and the second brace is an initializer block. Due to the need for creating an inner class the use of double brace initialization is considered to be slower.

Because of this performance issue it’s better not to use this technique for your production code, but using it in your unit testing can make your test looks simpler.

How do I get name of enum constant?

This example demonstrate how to user enum‘s name() method to get enum constant name exactly as declared in the enum declaration.

package org.kodejava.basic;

enum ProcessStatus {
    IDLE, RUNNING, FAILED, DONE;

    @Override
    public String toString() {
        return "Process Status: " + this.name();
    }
}

public class EnumNameDemo {
    public static void main(String[] args) {
        for (ProcessStatus processStatus : ProcessStatus.values()) {
            // Gets the name of this enum constant, exactly as
            // declared in its enum declaration.
            System.out.println(processStatus.name());

            // Here we call to our implementation of the toString
            // method to get a more friendly message of the
            // enum constant name.
            System.out.println(processStatus);
        }
    }
}

Our program result:

IDLE
Process Status: IDLE
RUNNING
Process Status: RUNNING
FAILED
Process Status: FAILED
DONE
Process Status: DONE

How do I use static import feature?

In order to use a static member of a class in Java we have to qualify the reference with the class name where they came from. For instance to access the PI and abs() from the Math class we should write:

double circle = Math.PI * 10;
int absolute = Math.abs(-100);

For some time you might want to call the members without the class name. This is allowed in Java 5.0 by using a feature called static import. It’s an import statement that allows you to statically import static class member. A static import declaration enables you to refer to imported static members as if they were declared in the class that uses them, the class name and a dot (.) are not required to use an imported static member.

You can write something like the following to static import.

import static java.lang.Math.PI;
import static java.lang.Math.*;

For a clear code it is better to import each member separately and not using the “*” to import every static member in your code.

Let’s see a simple static import below:

package org.kodejava.basic;

import java.util.Date;

import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.System.out;

public class StaticImport {
    public static void main(String[] args) {
        // Using static field PI and static method abs() from the
        // java.lang.Math class.
        double circle = PI * 10;
        int absolute = abs(-100);

        // Using static field of the java.lang.System class to
        // print out the current date.
        out.println("Today: " + new Date());
    }
}

How do I get ordinal value of enum constant?

This example demonstrate the use of enum ordinal() method to get the ordinal value of an enum constant.

package org.kodejava.basic;

enum Color {
    RED, GREEN, BLUE
}

public class EnumOrdinal {
    public static void main(String[] args) {
        // Gets the ordinal of this enumeration constant (its
        // position in its enum declaration, where the initial 
        // constant is assigned an ordinal of zero)
        System.out.println("Color.RED  : " + Color.RED.ordinal());
        System.out.println("Color.GREEN: " + Color.GREEN.ordinal());
        System.out.println("Color.BLUE : " + Color.BLUE.ordinal());
    }
}

The program print the following result:

Color.RED  : 0
Color.GREEN: 1
Color.BLUE : 2