How do I get all available currency codes?

The example presented in this code snippet show you how to get the available currency codes. We will need the locale information and use the Currency class for this example.

package org.kodejava.example.util;

import java.util.Currency;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

public class CurrencySymbolDemo {
    public static void main(String[] args) {
        CurrencySymbolDemo cs = new CurrencySymbolDemo();

        Map<String, String> currencies = cs.getAvailableCurrencies();
        for (String country : currencies.keySet()) {
            String currencyCode = currencies.get(country);
            System.out.println(country + " => " + currencyCode);
        }
    }

    /**
     * Get the currencies code from the available locales information.
     *
     * @return a map of currencies code.
     */
    private Map<String, String> getAvailableCurrencies() {
        Locale[] locales = Locale.getAvailableLocales();

        // We use TreeMap so that the order of the data in the map sorted
        // based on the country name.
        Map<String, String> currencies = new TreeMap<>();
        for (Locale locale : locales) {
            try {
                currencies.put(locale.getDisplayCountry(),
                    Currency.getInstance(locale).getCurrencyCode());
            } catch (Exception e) {
                // when the locale is not supported
            }
        }
        return currencies;
    }
}

You will have something like this printed on the screen:

...
Honduras => HNL
Hong Kong => HKD
Hungary => HUF
Iceland => ISK
India => INR
Indonesia => IDR
Iraq => IQD
Ireland => EUR
Israel => ILS
Italy => EUR
...

How do I create a Locale object using a variant?

Font differences may force you to use different characters on different platforms. You could then define the Locale objects with the variant codes to identify those differences. The variant codes conform to no standard. They are arbitrary and specific to your application. If you create Locale objects with variant codes only your application will know how to deal with them.

In this example instead of demonstrating to use a different font for different platform we simplify it to just print a different message. We create three different resource bundles for each platform, the MessagesBundle_fr_FR_UNIX.properties, MessagesBundle_fr_FR_MAC.properties and MessagesBundle_fr_FR_WIN.properties. These files will contains different message for each platform.

package org.kodejava.example.util;

import java.util.Locale;
import java.util.ResourceBundle;

public class LocalePlatform {
    public static void main(String[] args) {
        ResourceBundle res;
        String language = "fr";
        String country = "FR";

        // Construct a locale from language, country, variant. Where the variant
        // can be a variant vendor and browser specific code.
        Locale unix = new Locale(language, country, "UNIX");
        res = ResourceBundle.getBundle("MessagesBundle", unix);
        System.out.println("UNIX: " + res.getString("birthday"));

        Locale mac = new Locale(language, country, "MAC");
        res = ResourceBundle.getBundle("MessagesBundle", mac);
        System.out.println("MAC : " + res.getString("birthday"));

        Locale windows = new Locale(language, country, "WIN");
        res = ResourceBundle.getBundle("MessagesBundle", windows);
        System.out.println("WIN : " + res.getString("birthday"));
    }
}

Here are the contents of the resource bundle files:

MessagesBundle_fr_FR_UNIX.properties

birthday=Unix, Joyeux anniversaire à vous!

MessagesBundle_fr_FR_MAC.properties

birthday=Mac, Joyeux anniversaire à vous!

MessagesBundle_fr_FR_WIN.properties

birthday=Windows, Joyeux anniversaire à vous!

How do I get all available Locale language codes?

When you want to internationalize your application, you need to know the language code and country code. These codes will be used as the properties file name (the file name must be ended in language_COUNTRY.properties). Here is an example that show how to get all supported language’s code.

package org.kodejava.example.util;

import java.util.Locale;

public class LocaleCountryLanguageCode {
    public static void main(String[] args) {
        // Gets an array of all installed locales. The returned array represents
        // the union of locales supported by the Java runtime environment and by 
        // installed LocaleServiceProvider implementations.
        Locale[] locales = Locale.getAvailableLocales();

        for (Locale locale : locales) {
            System.out.printf("Locale name: %s = %s_%s%n",
                locale.getDisplayName(), locale.getLanguage(), locale.getCountry());
        }
    }
}

Here a some of the results produces by the code above:

...
...
Locale name: Japanese (Japan) = ja_JP
Locale name: Spanish (Peru) = es_PE
Locale name: English (United States) = en_US
Locale name: French (Belgium) = fr_BE
Locale name: Indonesian (Indonesia) = in_ID
Locale name: German (Germany) = de_DE
Locale name: English (Singapore) = en_SG
...
...

How do I use the SortedMap interface?

package org.kodejava.example.util;

import java.util.*;

public class SortedMapDemo {
    public static void main(String[] args) {
        SortedMap<String, String> sorted = new TreeMap<>();
        sorted.put("United States", "New York");
        sorted.put("United Kingdom", "London");
        sorted.put("Netherlands", "Amsterdam");
        sorted.put("Japan", "Tokyo");
        sorted.put("France", "Paris");

        // Gets the first(lowest) key currently in this map
        String firstKey = sorted.firstKey();

        // Gets the last (highest) key currently in this map
        String lastKey = sorted.lastKey();

        System.out.println("First key: " + firstKey);
        System.out.println("Last key : " + lastKey);

        // Gets a view of the portion of this map whose keys range
        // from fromKey(Japan), inclusive, to toKey(United Kingdom),
        // exclusive. (If fromKey and toKey are equal, the returned
        // map is empty.)
        SortedMap<String, String> sub = sorted.subMap("Japan",
            "United Kingdom");
        Set<String> subKeys = sub.keySet();
        System.out.println("\nSub Map: ");
        System.out.println("============");
        for (String key : subKeys) {
            System.out.println(key);
        }

        // Gets a view of the portion of this map whose keys are
        // strictly less than toKey(in this example is Netherlands)
        SortedMap<String, String> head = sorted.headMap("Netherlands");
        Set<String> headKeys = head.keySet();
        System.out.println("\nHead Map:");
        System.out.println("============");
        for (String key : headKeys) {
            System.out.println(key);
        }

        // Gets a view of the portion of this map whose keys are
        // strictly greater than or equal fromKey(in this example
        // is Netherlands)
        SortedMap<String, String> tail = sorted.tailMap("Netherlands");
        Set<String> tailKeys = tail.keySet();
        System.out.println("\nTail Map:");
        System.out.println("============");
        for (String key : tailKeys) {
            System.out.println(key);
        }
    }
}

Here is the output of the program:

First key: France
Last key : United States

Sub Map: 
============
Japan
Netherlands

Head Map:
============
France
Japan

Tail Map:
============
Netherlands
United Kingdom
United States

How do I convert a Vector into an array?

This example demonstrates how to convert a Vector object into an array. You can use the Vector.copyInto(Object[] array) method to create a copy of the Vector object in array form.

package org.kodejava.example.util;

import java.util.Vector;

public class VectorToArray {
    public static void main(String[] args) {
        Vector<Integer> vector = new Vector<>();
        vector.add(10);
        vector.add(20);
        vector.add(30);
        vector.add(40);
        vector.add(50);

        // Declares and initializes an Integer array.
        Integer[] numbers = new Integer[vector.size()];

        // Copies the components of this vector into the specified
        // array of Integer
        vector.copyInto(numbers);

        for (Integer number : numbers) {
            System.out.println("Number: " + number);
        }
    }
}        

The result of the code snippet above:

Number: 10
Number: 20
Number: 30
Number: 40
Number: 50

How do I remove elements from Deque?

This example shows you how to removes some elements from the Deque object. We can use the following methods for removing elements from Deque: remove(), remove(Object o), removeFirst(), removeLast().

package org.kodejava.example.util;

import java.util.Deque;
import java.util.LinkedList;

public class RemoveDequeDemo {
    public static void main(String[] args) {
        Deque<String> deque = new LinkedList<>();
        deque.add("A");
        deque.add("B");
        deque.add("C");
        deque.add("D");
        deque.add("E");
        deque.add("F");

        // Removes and retrieves the head of this Deque
        deque.remove();      // Removes "A"

        // Removes the first occurrence of element from this Deque
        deque.remove("F");   // Removes "F"

        // Retrieves and removes the first element of this deque
        deque.removeFirst(); // Removes "B"

        // Retrieves and removes the last element of this deque
        deque.removeLast();  // Removes "E"

        for (String item : deque) {
            System.out.println("Item = " + item);
        }
    }
}

How do I add elements into a Deque?

To add elements into a Deque object we can use the add(), addFirst() and addLast() method call.

package org.kodejava.example.util;

import java.util.Deque;
import java.util.LinkedList;

public class DequeAddElement {
    public static void main(String[] args) {
        // Create an instance of Deque using LinkedList class.
        Deque<String> deque = new LinkedList<>();

        // Insert a word into the Deque
        deque.add("jumps");

        // Insert words at the beginning of the current Deque
        // elements
        deque.addFirst("fox");
        deque.addFirst("brown");
        deque.addFirst("quick");
        deque.addFirst("The");

        // Insert words at the end of the current Deque elements
        deque.addLast("over");
        deque.addLast("the");
        deque.addLast("lazy");
        deque.addLast("dog");

        for (String word : deque) {
            System.out.println("Word = " + word);
        }
    }
}

Here is the output:

Word = The
Word = quick
Word = brown
Word = fox
Word = jumps
Word = over
Word = the
Word = lazy
Word = dog

How do I create a Hashtable and iterates its contents?

The code snippet shows you how to create and instance of Hashtable that stores Integer values using a String keys. After that we iterates the elements of the Hashtable using the Enumeration interface.

package org.kodejava.example.util;

import java.util.Enumeration;
import java.util.Hashtable;

public class HashtableDemo {
    public static void main(String[] args) {
        // Creates an instance of Hashtable
        Hashtable<String, Integer> numbers = new Hashtable<>();
        numbers.put("one", 1);
        numbers.put("two", 2);
        numbers.put("three", 3);

        // Returns an enumeration of the keys in this Hashtable
        Enumeration<String> keys = numbers.keys();
        while (keys.hasMoreElements()) {
            // Returns the next element of this enumeration if this
            // enumeration object has at least one more element to
            // provide
            String key = keys.nextElement();
            System.out.printf("Key: %s, Value: %d%n", key, numbers.get(key));
        }
    }
}

How do I create Deque using ArrayDeque class?

This example show you how to create a Deque using the ArrayDeque implementation. The ArrayDeque stores its elements using an array. If the number of elements exceeds the space in the array, a new array will be allocated, and all elements moved the the new allocated array.

In the code below we initiate the size of the Deque to store five elements. When we add the element number six the array that stores the elements of the Deque will be resized.

package org.kodejava.example.util;

import java.util.ArrayDeque;
import java.util.Deque;

public class ArrayDequeDemo {
    public static void main(String[] args) {
        // Constructs an empty array deque with an initial capacity
        // sufficient to hold the specified number of elements.
        Deque<Integer> deque = new ArrayDeque<>(5);
        deque.add(1);
        deque.add(1);
        deque.add(2);
        deque.add(3);
        deque.add(5);        
        deque.add(8);
        deque.add(14);
        deque.add(22);

        for (Integer number : deque) {
            System.out.println("Number = " + number);
        }
    }
}

How do I read Vector object using Enumeration?

The following code snippets show you how to iterate and read java.util.Vector elements using the java.util.Enumeration.

package org.kodejava.example.util;

import java.util.Enumeration;
import java.util.Vector;

public class VectorEnumeration {

    public static void main(String[] args) {
        Vector<String> data = new Vector<>();
        data.add("one");
        data.add("two");
        data.add("three");

        StringBuilder sb = new StringBuilder("Data: ");

        // Iterates vector object to read it elements
        for (Enumeration enumeration = data.elements();
             enumeration.hasMoreElements();) {
            sb.append(enumeration.nextElement()).append(",");
        }

        // Delete the last ","
        sb.deleteCharAt(sb.length() - 1);
        System.out.println(sb.toString());
    }
}